开发者

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.


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; }
}


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);


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


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.


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.


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;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜