callisto
callisto

Reputation: 5083

Making a property compulsory

Is there any way to make a property that is defined in a class compulsory?
I want the compiler to complain if the object is declared and used without the compulsory property.

Upvotes: 3

Views: 1169

Answers (6)

Emond
Emond

Reputation: 50692

A way might be to implement a constructor that forces the creation of an object to have an initial value for a property:

class Demo
{
    public int P {get; set;}

    Demo(int p)
    {
        P = p;
    }
}

Now the client can only create the object by passing a value for p:

var d = new Demo(42);

Upvotes: 3

Stecya
Stecya

Reputation: 23276

make default constructor private and define constructor that will get needed value for your property

public YourClass(string value)
{
   YourCompulsaryProperty = value;
}

public string YourCompulsaryProperty{get; set;}

Upvotes: 1

Femaref
Femaref

Reputation: 61497

No, you can't force somebody to provide information to a property.

However, you can go the normal route, and make the constructor require the information. That way, the object can't be constructed without providing the information you need.

Upvotes: 3

SWeko
SWeko

Reputation: 30912

How about adding a constructor to the class that would take a value for the property?

public class MyClass 
{     
   public int Mandatory {get; set;}
   public int Optional {get; set;}

   public MyClass(int mandatory)
   {
      Mandatory = mandatory;
   }

   public MyClass(int mandatory, int optional)
   {
      Mandatory = mandatory;
      Optional = optional;
   }
}

This way, the class can be instantiated using either the one or two-parameter constructor, so the user will have to specify a value for the Mandatory property.

MyClass x = new MyClass();   // does not compile
MyClass x = new MyClass(1);  //Mandatory = 1; Optional = 0 (default value)
MyClass x = new MyClass(1,2);//Mandatory = 1; Optional = 2

Upvotes: 3

Vadim
Vadim

Reputation: 17955

Best approach I would think would be to not specify a default constructor.

public class MyClass
{
    public MyClass(string myProp)
    {
        MyProp = myProp;
    }

    public string MyProp { get; set; }
}

Upvotes: 6

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

You can just add a constructor to your class that accepts one parameter - the value for your property. Like this, the property is always initialized after an instance of the class is created.

Upvotes: 1

Related Questions