Protected member field and its property - c#

Suppose you have the following A class definition:
class A
{
protected double[] _temperatures;
double[] Temperature
{
get {return _temperatures;}
set {_temperatures = value;}
}
}
How should I access temperatures in a derived class B? Using the member field or the property? Should I declare _temperatures as private and always use the property? What is the overhead of using the property instead of direct member field access?
Thanks.

You should use the property and make the field private. But your code with a custom private field only make sense if you really need to add some custom logic in the getter or setter. So for your simple case, you can go with this:
class A
{
protected double[] Temperature { get; set; }
}

Yes change the data member to private. Using a Property instead of a Field (private member) is a better way of accessing it even if its from within the same class so that if you have some logic in the getter/setter you don't have to repeat it each time you set the value.
Even if you don't have logic its better to use property as you might need to add some logic in future. It will be a single point of entry for getting and setting the value.
And yes as Kevin suggested you can use auto-implemented property if you don't have custom logic.

You may modify your code like this:
class A
{
private double[] _temperatures;
public double[] Temperature
{
get { return _temperatures; }
set { _temperatures = value; }
}
}
class B : A
{
public B()
{
B b = new B();
Console.WriteLine(b.Temperature);
}
}
Local variable '_temperatures' should be private and property 'Temperature' should be either public or protected.

Ideally a class should not expose its members (in your case _temperatures) to the outside world. Members are meant to be used internally with in a class. If you want to expose a class member then use properties. Thats ideal way of designing a class.
The advantage of this type of class designing is tomorrow suppose there is a need to add some logic when assigning a value or retrieving a value from a class member then it can be easily accomodated with in a property without redesigning the interface.
So declare _temperatures as private and expose it to derived classes by declaring the property Temperature as protected.
Refer this C# tutorial for additonal information:

Related

this or base? In which case could we use base instead of this?

In the following code
// MVVM Views part class
public partial class DashBoard : UserControl
{
public DashBoard()
{
InitializeComponent();
this.DataContext = new DashBoardViewModel();
}
}
Could we use base.DataContext instead this.DataContext. In which case could we use base instead of this?
It's usually clearer to use this. You normally only specify base when you want to explicitly call a base class constructor or the base implementation of an overridden method or property.
Using base.DataContext would work, but it would might imply that this.DataContext would mean something different.
You use this to access a method defined in the present class (or superclass if it's not in the present class). You use base to access a method in the superclass or higher. In this case you could have used either (or none as Marc points out above).
I prefer to emit this except when it's (rarely) required.
To add to what the others have said, base. is used when you've overridden something from the base class with either the overrides or new keywords, you'll need to use base to gain access to the original method.
class a
{
public virtual void method1()
{
}
public string property1 { get; set; }
}
class b : a
{
// this has it's own instance in b, the only way to get to
// the original property1 is with base (or reflection)
public new string property1 { get; set; }
public override void method1()
{
// the only way to get to the original method1 and property1
base.method1();
base.property1 = "string";
}
}
In your example if the DataContext property uses either of these keywords then base and this don't mean the same thing at all.
Considering your case u are trying to initialize DataContext property of class DashBoard with some value. So if you then call DataContext typed property of (base)UserControl class object, it still will be not initialized. Therefore, to decide which property to initialize, u must to look to your program's logic.
Basicly MSDN tells that u should use (base.) in two scenarious:
-Call a method on the base class that has been overridden by another method.
-Specify which base-class constructor should be called when creating instances of the derived class.
In my practise i used first scenario when (this) method ends with exception, i was trying to call more general (base) method. Good luck!

Automatically generated property {get; set;} vs {get; private or protected set;} in C#

I see a lot of code uses automatically generated property like {get; private set;} or {get; protected set;}.
What's the advantage of this private or protected set?
I tried this code, but it's the same when I have Foo{get; set;}.
public class MyClass
{
public int Foo {get; private set;}
public static void RunSnippet()
{
var x = new MyClass();
x.Foo = 30;
Console.WriteLine(x.Foo);
}
...
}
It makes a property read-only by external sources (i.e. classes that aren't MyClass and/or its subclasses). Or if you declared the property protected with a private set, it's read-only by its subclasses but writable by itself.
It doesn't make a difference in your class because your setter is private to that class, so your class can still access it. However if you tried to instantiate MyClass from another class, you wouldn't be able to modify the Foo property's value if it had a private or protected setter.
private and protected mean the same here as they do elsewhere: private restricts access only to that very class, while protected restricts access to that class and all its derived classes.
It makes a difference when you have a class model that uses inheritance. If your MyClass methods are clients of your private fields and methods it makes no difference.
That said, even if you don't anticipate your MyClass becoming a parent class in any sort of class hierarchy, it doesn't hurt to limit your field and method scope to the least visible scope that it requires. Encapsulate what you can with the least visible scope by default so that you don't have to refactor when subclasses start to access parent properties that they shouldn't be. The level of effort isn't any different from not doing so.
If you specify no access modifiers on the get and set keywords, the property will be accessible according to the access modifier of the property itself. In your example, you would be able to get the value of Foo and set the value of Foo from anywhere in your program if you specify get instead of private get.
In order to write robust code, you should try to always choose the most restrictive access modifier possible. It is a good idea to use properties to expose the state of your object, but not to change the state of your object from outside. If you want to change the state of your object, use method calls instead.
Think of the get and set functions in terms of accessor and mutator methods (except that you don't have to explicitly write the method bodies out:
private int foo;
public int get_Foo()
{
return foo;
}
public /* or protected, or private */ void set_Foo(int value)
{
foo = value;
}
After you see it like that, know that the protected and private modifiers work the same on a setter as they do on any other sort of member.

C#, accessing a variable from a class?

Say i have
public int MyVariable;
in the Form1.cs file, and I want to access it from Class1.cs , what do you think would be the best way to do that?
Thanks!
MSDN: Properties
base class with property:
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Auto Implemented Properties (if advanced work on "name" isn't needed):
class Person
{
public string Name { get; set; } // the Name property with hidden backing field
}
Class accessing the property:
Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here
System.Console.Write(person.Name); // the get accessor is invoked here
It depends on the scenario. But ideally, Form elements are passed to any functions that will need to use them.
You have a few options:
Pass the value to the class/method that's using it. This is the preferred scenario. If your class depends on this value, supply the value to the class. Don't make the class go looking for it. (See: Dependency Inversion Principle)
Make the value static. Then any other class can refer to that value. Note the difference between instance and static, of course. The value will always be the same and needs to be given in the definition of the member, not in a constructor or other logic.
Create an instance of the form (which is itself just a class) within the class and access the public member on that instance. This is unlikely to be what you want because the instance you're creating isn't the instance that's running "on the page." (It also violates the principle noted above.)
Pass a reference to the form (this) to the class and refer to the member from that reference.
On a side note, you'll want to get in the habit of making your public members properties instead of variables. In most cases, the property will likely just get/set the variable and nothing more. However, if something more ever needs to be added it can be done so without breaking compatibility. Changing a variable to a property changes the footprint of the class and breaks things which use that class.
Make the variable static. Then you can call it like Form1.MyVariable.
Try like this:
In case (1) you can have MyClass.MyInt private readonly.
public class MyForm : System.Windows.Forms.Form
{
int myInt;
public MyForm()
{
myInt = 1;
//1
var myClass = new MyClass(myInt);
//2
myClass.MyInt = myInt;
}
}
public class MyClass
{
public int MyInt { get; set; }
public MyClass(int myInt)
{
MyInt = myInt;
}
}

C# - What should I do when every inherited class needs getter from base class, but setter only for ONE inherited class

I have a abstract class called WizardViewModelBase.
All my WizardXXXViewModel classes inherit from the base abstract class.
The base has a property with a getter. Every sub class needs and overrides that string
property as its the DisplayName of the ViewModel.
Only ONE ViewModel called WizardTimeTableWeekViewModel needs a setter because I have to set
wether the ViewModel is a timetable for week A or week B. Using 2 ViewModels like
WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant.
I do not want to override the setter in all other classes as they do not need a setter.
Can I somehow tell the sub class it needs not to override the setter?
Or any other suggestion?
With interfaces I would be free to use getter or setter but having many empty setter
properties is not an option for me.
Funny.. I have just thought what would happen if I really would need to SET all DisplayNames of the WizardPages contrary what I said firstly. Maybe I should not hardcode the strings in the getter and put the strings in a reesource file because of localization, then I need a setter anywhere in every sub class XD
Don't declare the setter method as virtual.
If for some reason (I can't think of one!) you need for it to be virtual at the top of your inheritance hierarchy then use sealed when you override it:
http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx
If the property is not abstract, then any base class may choose to only override the setter, the getter, or both.
If you want your subclasses not to have access to your setter, except for only a given subclass, you can use the internal access modifier only to the getter, and implement classes that shouldn't have access to the setter in another assembly.
You should introduce a new abstract class, which will inhere WizardViewModelBase class. That class should override a property using both get and set accessors, but will leave a property abstract, like this:
public abstract string DisplayName
{
get;
set;
}
Then you can use this class as a base class for WizardTimeTableWeekViewModel class and you wil be able to override both get and set accessors.
I'd use a protected setter and create a seperate function to set the value. After all the class does not have the same interface as the others so distinguishing it visibly from the others should help readability.
class Base
{
public String Value { get; protected set; }
}
class SpecialChild : Base
{
public void SetValue(String newValue) { this.Value = newValue; }
}
// Somewhere else
SpecialChild special = foo as SpecialChild;
if (special != null)
{
special.SetValue('newFoo');
}
else
{
foo.DoSomeStuff();
}

Setting private property value in constructor of inherited class

I've got a base class from an outside library that I can't modify - here's the relevant piece:
public class BaseClass
{
List<string> _values;
public Values { get { return _values; } }
}
I am inheriting the BaseClass, and I want to set _values to a class that inherits from List(T) in the constructor:
public InheritingClass : BaseClass
{
public InheritingClass():base()
{
//set base._values = new InhertingList<string>(); ?
}
}
What's the best way to set base._values there? Is there a way to find what private variable is fetched by Values and set that in case the private variable is renamed in the future?
There are other ways I can accomplish what I need to do, but if I could do the following, it would be quicker by far than any ways of achieving my goal without setting the private property value.
Keeping it private, by definition, is meant to prevent this exact scenario.
The best option would be to implement a protected setter:
public class BaseClass
{
public Values {
get { return _values; }
protected set { _values = value; }
}
}
This way, your InheritingClass has access to the setter, and can do:
this.Values = new InhertingList<string>();
But since you can't change the base class, it is, technically, possible to do this via reflection (in a full trust scenario). I don't recommend this approach, though:
FieldInfo field = typeof(BaseClass).GetField("_value", BindingFlags.Instance | BindingFlags.NonPublic );
field.SetValue(this, this.Values = new InhertingList<string>() );
The danger of doing what you are attempting, btw, is that you're going to change the implementation defined by the BaseClass to something that you're providing. It's very easy to introduce subtle bugs, since you're (purposefully) "breaking" the implementation details in the base class.
I'd try to rethink your algorithm, and see if there's another way around this issue.
If you really need to set the value, you can use reflection. But that's no good coding style and may be slow.
Edit:
It might be possible to disassemble your BaseClass and change its implementation. Bun then you might have to disassemble the whole library.
Perhaps you can provide some more details on your problem?
Usually, when you don't have a property with an accessible setter provided for a field, it means that you should not modify that field from anywhere but the BaseClass - if the creator of the BaseClass class would have wanted you to be able to modify that field, he'd have exposed a property with a protected setter or something like that. So generally it's not recommended to hack it.
You could certainly do it by reflection though, providing you know the name of the private field - I don't think it is possible to extract the body of the property.
As for the other answers: he wrote "I've got a base class from an outside library that I can't modify".
You can't set the private property. You will either have to inherit from another base class or create your own base class that provides the behaviour.
Of course, depending on the level of trust your application is running under, you may be able to set the private variable via reflection but that would really be a hack to get around what is actual a problem in the design.
No, there is no way to do what you're looking for. Private variables are meant to be private - namely, they can't be seen or altered by any code.
Normally, when fields don't have mutator methods, you'd use the constructor of the class to instantiate the object (and it's relevant fields).
BaseClass base = new BaseClass(List<string> yourList);
You could always utilize the "new" keyword, but the inherited method would be ignored if the class is cast back to its base object
public InheritingClass : BaseClass
{
public InheritingClass()
{
Values = new InhertingList<string>(); ?
}
public new List<string> Values { get; private set; }
}
To access private fields you can use Reflection, but since the field is private I'm not certain how the inheriting class would benefit from changing a private field type.
public InheritingClass : BaseClass
{
private static FieldInfo _valueField = typeof(BaseClass).GetField("_values", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
public InheritingClass()
{
_valueField.SetValue(this, new InhertingList<string>());
}
}
http://msdn.microsoft.com/en-us/library/6z33zd7h(v=vs.110).aspx

Categories

Resources