سؤال

I am accessing fields of a class and if I use them as static I can use them from the class without creating an instance of the class which means less code. But should I? What is the best practice?

public class myClass
{
    private static DataSet myDS;
    myClass.myDS = new DataSet();
}

or

private DataSet myDS;

public DataSet MyDS
{
    get { return myDS; }
    set { myDS = value; }
}

myClass a = new myClass();
a.MyDS = new DataSet();
هل كانت مفيدة؟

المحلول

It all depends on how you want to use the members of your class and how you want control access to those members. It has nothing to do with writing less code. In the example you provided if you wanted to use the same DataSet across all instances of "myClass", or across the your application if the property were public/internal, then make it static. If you require a new DataSet each time you create an instance of "myClass", then make it non-static.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top