This is probably a simple C# question for somebody, who has been working in it for long enough. Can I do something like this

class MyClass
{
    public string Name { get; set; }

    public void SetName(string name)
    {
        Name = name;
    }
}

Then inside some other class I have something like this

    MyClass myClass;

    public MyClass MyProperty { get { return myClass ?? new    MyClass().SetName("myName"); } }

So when I call Myproperty if it is null I want to just create a new one with a property set this way, I cannot use constructor on MyClass, instead I have few overloaded methods, that I call when MyClass is constructed.

This works

   public MyClass MyProperty
    {
        get
        {
            myClass = myClass ?? new MyClass();
            myClass.SetName("myName");
            return myClass;
        }
    }

But I’m just curious why this does not, what is the difference because I don’t see any

public MyClass MyProperty 
{ 
   get 
   { 
      return myClass ?? new    MyClass().SetName("myName"); 
   }
}

EDIT:

I just did this instead based on the opinions

public MyClass MyProperty 
{ 
   get 
   { 
            if (myClass == null)
            {
                myClass = new MyClass();
                myClass.SetName("myName);
            }
            return repository;
   }
 }

Another approach is to change MyClass to

class MyClass
{
    public string Name { get; set; }

    public MyClass SetName(string name)
    {
        Name = name;
        return this;
    }
 }

and then use it like this

    MyClass myClass;
    public MyClass MyProperty
    {
        get
        {
            return myClass ?? new MyClass().SetName("myName");
        }
    }

And Im going with it :0 Thanks for all answers :)

1

There are 1 answers

4
Andrey Korneyev On BEST ANSWER

Return type of SetName is void.

So new MyClass().SetName("myName") is void, not instance of MyClass.

UPDATE

To achieve your desired behaviour, you can change SetName to return this, and rewrite your MyProperty setter for example, to return myClass ?? new MyClass().SetName("myName");