user12096997
user12096997

Reputation:

Is it possible to get only initialized properties in a C# class

I have a class as follows

public class SampleClass{

  public string Property1 {get; set;}

  public string Property2 {get; set;}

  public string Property3 {get; set;}

}

Then I create an initialization of this class only with two properties and send it through some method. Here, I get all the 3 properties but how can I differentiate whether the 3rd property is initialized or not while accessing within the method?.

var classInstance = new SampleClass {
  Property1 = "one",
  Property2 = "two"
};

this.SomeMethod(classInstance);

// Is it possible to get that the third property is not defined in the class instance in this method?

Upvotes: 0

Views: 494

Answers (3)

Alpesh Vaghela
Alpesh Vaghela

Reputation: 107

You need to add constructor and initialize properties in it. it will works fine then.

public class sampleClass
{
    public sampleClass(){
     this.Init();
    }

    public string property1 {get; set;}
    public string property2 {get; set;}
    public string property3 {get; set;}

    private void Init()
    {
        this.property1 = "one";
        this.property2 = "two";
    }
}

Upvotes: 0

Jonas Høgh
Jonas Høgh

Reputation: 10874

First, these are properties, not attributes. Attributes are a different language construct in C#. We've edited your question accordingly.

Second, using an object initializer as in your example with classInstance is equivalent to calling the default constructor, then the setter of the two first properties.

Since the default constructor is empty in your class, all 3 properties will be null after calling it. This is because string is a reference type, and all reference types have a default value of null. Then Property1 will be set to "one", Property2 to "two", and Property3 will keep the null value.

It is not the case that Property3 is not defined on classInstance . It simply has the value null.

Upvotes: 4

Platypus
Platypus

Reputation: 361

This could be what you're looking for ?
A custom constructor

public class SampleClass
    {
        public SampleClass(string property1, string property2)
        {
            this.Property1 = property1;
            this.Property2 = property2;
            this.Property3 = null;
        }

        public string Property1 { get; set; }

        public string Property2 { get; set; }

        public string Property3 { get; set; }

    }

I'm not sure of what you're using it for though, but maybe if you've many different conditional use cases like this one, a class that do it all is maybe the best solution.
Let us know.

Upvotes: 0

Related Questions