Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c# - Cannot implicitly convert type 'void' to 'System.Collections.Generic.Dictionary<string,bool>

This code works fine

Dictionary<string, bool> test = new Dictionary<string, bool>();
        test.Add("test string", true);

The following code throws this error : Cannot implicitly convert type 'void' to 'System.Collections.Generic.Dictionary

Dictionary<string, bool> test = new Dictionary<string, bool>().Add("test string", true);

why? what is the difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The return type of .Add is void

If you are chaining calls, the last expression becomes the return value of the whole statement.

The return value of new Dictionary<K, V>() is Dictionary<K, V>, then you call .Add on it and .Add returns nothing (void)

You can use object initialiser syntax to do this inline:

Dictionary<string, bool> test = new Dictionary<string, bool> 
{ 
    { "test string", true } 
};

Edit: more info, a lot of fluent syntax style frameworks will return the object you called the method on to allow you to chain:

e.g.

public class SomeFluentThing 
{
   public SomeFluentThing DoSomething()
   {
       // Do stuff
       return this;
   }

   public SomeFluentThing DoSomethingElse()
   {
       // Do stuff
       return this;
   }

}

So you can chain naturally:

SomeFluentThingVariable.DoSomething().DoSomethingElse();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...