4
Answers

Is Possible,single Property use for 5 more same type fields?

Arun Kurmi

Arun Kurmi

12y
1.1k
1
hi friends,
I have a class Student.Where i declare 5 private field:
marksInMaths,marksInEng,marksInPhy,marksInChem and marksInHin.Then i created a seperate property with get{} and set{} for each namely Math,Phy,Chem,Eng and Hin. All the properties have same purpose for their respective subject.So i think  if it is Possible perform  all the five properties task in  a single property then reduce my code.Is Possible??? if yes then please give an example.
Answers (4)
0
Vulpes

Vulpes

NA 98.3k 1.5m 12y
If you want to cut down on code and all that your properties are doing is getting the private field or setting it to 'value', then you can use 'automatic' properties instead.

In general, if you have this:

  private SomeType fieldName;

  public SomeType PropertyName
  {
     get { return fieldName; }
     set { fieldName = value; }
  }


then you can replace it with this:

  public SomeType PropertyName { get; set; }

When you use an automatic property the compiler creates the private field in the background and expands the property declaration accordingly. As the field is hidden you must always access it via the property which is no problem in practice.

'SomeType' can represent any type you like.


Accepted
1
Jignesh Trivedi

Jignesh Trivedi

NA 61k 14.2m 12y

yes, agree with vulpes, if you want to reduce the code and if your using .net framework 3.0 or above than you can use auto implemented properties.

as per my understanding all subjects are differnt entity and has different value right?

0
Arun Kurmi

Arun Kurmi

NA 106 72.8k 12y
But,Jignesh in my example case All 5 Are subject so using property for all is same purpose so if we done this task in single property then it reduce 4 properties from the code.If we done this then it is better than using 5 properties.So if any one have idea then please tell me with syntax....
0
Jignesh Trivedi

Jignesh Trivedi

NA 61k 14.2m 12y
hi,

it is good idea to use different property for different purpose. in your code all five property has different meaning so as per me it is good to separate them other wise code might become very complicated.

hope this will help you.