Inheritance of C# private/protected members - c#

Some say here that if members are protected you can access them:
Are private members inherited in C#?
Did someone really tried ?
I have tried it doesn't even work with protected:
public partial class Base
{
protected IObject myObject;
}
If I derive (Base is in another namespace but it shouldn't matter I of course import that namespace)
public partial class Derive: Base
{
}
Intellisense doesn't show myObject in Derive Class.
So what I can do if I need a myObjhect member in all my derived classes to call some methods upon ? If I have to duplicate that member then what's the use of inheritance ?
Update: I forgot Derive:Base but that was just mystypo, of course I did that.

You aren't deriving. To derive, you have to do the following:
public class Base
{
protected IObject myObject;
}
public class Derive : Base
{
}
myObject is available in Derive now. Partial means you are splitting the class definition over multiple files.

You have to actually derive from the Base class:
public partial class Derive : Base
{
}

A derived class has access to the
public, protected, internal, and
protected internal members of a base
class. Even though a derived class
inherits the private members of a base
class, it cannot access those members.
However, all those private members are
still present in the derived class and
can do the same work they would do in
the base class itself. For example,
suppose that a protected base class
method accesses a private field. That
field has to be present in the derived
class in order for the inherited base
class method to work properly.
From: http://msdn.microsoft.com/en-us/library/ms173149.aspx
check this

Aren't you missing the base class when deriving? Should work with myObject declared as protected.
public partial class Derive : Base
{
}

Related

Create a UserControl derived from an abstract base class, and give it an X:Name?

I have a non-abstract user control derived from an abstract base class and therefore I have to use the abstract base class in the XAML code as the base. This is valid c# code in terms of type inheritance and class instantiability. It seems that the designer has problems with it:
MC3054: The type "MyAbstractClass" cannot have a Name attribute. Value types and types without default constructor can be used as items within a ResourceDictionary
I have the following type hierarchy:
public interface IMyInterface { void Init(); }
public abstract class MyAbstractClass: UserControl, IMyInterface
{ public abstract void Init(); }
public MyDerivedClass: MyAbtractClass
{ public void Init() {} }
and the following xaml section
< local:MyAbstractClass x:Name="myObject" x:Class="MyDerivedClass"
xmlns:local="clr-namespace:MyNameSpace" >
...
When I compile it I get the MC3054 error from title.
Changing the abstract class into non abstract makes it compilable and executable.
Why isn't it possible to use an abstract base class in xaml in this way, when the derived class is not abstract?
My abstract and derived classes have default constructors explicitly defined.

Abstract and concrete classes - getters and setters

How can I use setters in the concrete class? I have two abstract classes and the bottom concrete class should be able to set all the private variables I have the abstract classes, how can I do that?
I could just add getters and setters in my concrete class, but because I have 4 derived classes from my second abstract class, I don't want to have duplicate code and a long list of public properties, any way to resolve that?
I am working in C#
Using the protected keyword in c# you can access the variables in parent objects
Like this
public abstract class Parent {
protected int integer {get;set;}
}
public class Child : Parent {
public Child(int value) {
integer = value;
}
public int getValue() {
return integer;
}
}
see : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected
From Microsoft documentation :
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly.
private protected
The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
So doesn't matter if the class is abstract or not, private can only be accessed within the same class.

Restrict to use a class as a type in another class in c#

I have a class
abstract class EmployeeBase
{
}
I want that this EmployeeBase should not be used as a property in any of my other classes. Only a class derived from EmployeeBase can be used to declare a property in any other class. Is it possible to achieve that? If so, how?
You can get close to this this by making EmployeeBase a protected subclass of the class you wish to derive from:
public class OuterClass
{
protected abstract class EmployeeBase { /*...*/ }
}
However, keep in mind this will prevent any properties of type EmployeeBase from being exposed as public or internal, since you can't expose an object with a less exposed type, since any consuming code wouldn't know the signature of the object. EDIT You could, however, expose them by interface or other base type.
While you can restrict inheritance from EmployeeBase by making all constructors internal, restricting use of a type is not well supported in C#, and raises many questions about what exactly you're trying to do.
You cannot create instance of abstract class so there will be no variable or property created as EmployeeBase
You have to inherit from EmployeeBase so I believe your problem is already solved ;)
public abstract class EmployeeBase{}
public class Employee: EmployeeBase{}
class SomeClass
{
public EmployeeBase Employee { get; set; }
SomeClass()
{
Employee = new Employee(); // OOP in play :)
Employee = new EmployeeBase(); // Error CS0144
// Cannot create an instance of the abstract class or interface 'EmployeeBase'
}
}

Overriding Base Class abstract methods and hiding them in derived classes

I have two two types of base class;
public abstract class Base
{
public abstract object Work();
}
public abstract class AuthenticatedBase : Base
{
public abstract object Work(T request);
}
The authenticated class does some extra work to check a login beforehand. Then I have different classes extending from both base classes;
public class A : Base
{
public override object Work()
{
// Work here
}
}
public class B : AuthenticatedBase
{
public override object Work(T request)
{
// Work here
}
}
Basically, when I create a new class B that derives from AuthenticatedBase, Visual Studio says I need to implement Work() from the Base class even though I have an alternate implementation in AuthenticatedBase that I am overriding, admittedly with different parameters. What should I be doing so that I don't have to implement the Work() method from the base class in inherited classes?
Implement the parameterless Work method in your AuthenticatedBase and use the "sealed" keyword to stop it from showing on inheritors of AuthenticatedBase.
You have to implement it, there is no way around it. This is the case where multiple inheritance would come in handy.
You could use composition so that B has a reference to an A. Then B.Work() can call A.Work().
Alternatively, implement B.Work() so that it calls B.Work(T). Or even have Base.Work() be a virtual method with the base implementation from A.

Abstract class constructor in C#

In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.

Categories