Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are private static and instance variables inherited in C# and why?

Tags:

c#

inheritance

I have read that private variables in a base class are technically inherited by child classes, but are not accessible.

If this is correct, why do we say they are inherited when presumably they can only be accessed by reflection?

like image 634
Ben Aston Avatar asked Dec 18 '22 09:12

Ben Aston


1 Answers

Subclassing is about inheriting implementation; and fields are an implementation detail.

The fields are indeed present, and are available via reflection. But ultimately, it is the base-classes job to manage the state of those fields via any public/protected/etc members.

But ultimately - if a base-class declares a property (and field) for property Foo, then when you set that property the data has to go somewhere. The sub-class has to include all the fields from the base-class for it to make sense. This is also critical for field-based serialization frameworks (such as BinaryFormatter).

like image 198
Marc Gravell Avatar answered Dec 24 '22 00:12

Marc Gravell