How to return a FeatureLayer with QueuedTask.Run

791
4
Jump to solution
12-22-2021 08:27 AM
Amadeus111
Occasional Contributor II

I would like to refactor my code and implement a method instead of writing/copying the same code again again. 

I check TOC whether a certain Layer exists. If TOC does not have it I create the FeatureLayer. I use this process a lot in my applications. 

So, here is the method but it does not work

public Task<FeatureLayer> AddLayerToTOC(Uri layerUri, string layerName)
{
  return QueuedTask.Run(() =>
  {
    MainGridEnabled = false;

    FeatureLayer fLayer;
    TOCLayers = MapView.Active.Map.Layers;
    var TOCLayerNames = TOCLayers.Select(p => p.Name);

    if (TOCLayerNames.Contains(layerName) == false)
    {
     fLayer = LayerFactory.Instance.CreateFeatureLayer(layerUri, MapView.Active.Map, 0, layerName);
    }

    else
    {
       foreach (Layer layer in TOCLayers)
       {
          if (layer.Name == layerName)
          {
             fLayer = layer as FeatureLayer;;
          }
       }
  }

    MapView.Active.ZoomToSelected();

    MainGridEnabled = true;

    return fLayer;
    });
}

 

I get CS0165: Use of unassigned local variable

Problem coming from else {} part because VS thinks fLayer not assigned but I will do that while application is running. 

Is there a solution to this or another way of doing it? 

0 Kudos
1 Solution

Accepted Solutions
GKmieliauskas
Esri Regular Contributor

Hi,

It is simple. Set it to null:

FeatureLayer fLayer = null;

View solution in original post

0 Kudos
4 Replies
GKmieliauskas
Esri Regular Contributor

Hi,

It is simple. Set it to null:

FeatureLayer fLayer = null;
0 Kudos
Amadeus111
Occasional Contributor II

Hi @GKmieliauskas , 

I think I did not explain my situaton well. I don't want it to be null. I would like to return the fLayer to main thread either as a new layer or a Layer from the TOC. So, I can make queries, extract data, table etc.

Maybe, I should declare the fLayer as public and assign it after checking its existence. 

0 Kudos
GKmieliauskas
Esri Regular Contributor

Hi, 

Your code is fine. But compiler thinks that there is one situation when your method AddLayerToTOC could  return unassigned fLayer value. For example if your foreach cycle will not be executed. This is compiler problem, not yours.  And workaround for this is to preassign fLayer value with null in line 7.

Amadeus111
Occasional Contributor II

@GKmieliauskas

Thanks for the solution and detailed explanation, it worked very well. This will help me to reduce lotta repetition. 

0 Kudos