C# class inheritance doesn't work - c#

namespace MyProgram
{
public class ParentClass
{
}
public class childClass : ParentClass
{
public int Normal()
{
return 1;
}
}
}
SomeWhere else:
ParentClass parentc = new ParentClass();
parentc.Normal(); //<-- I can't call the function normal!
I need help, to use it.

Parent does not have a method Normal, so you can't call it. By basic logic, a parent does not inherit its child's methods; it's the other way around.

Move the normal method to the parent class:
public class ParentClass
{
public int Normal()
{
return 1;
}
}
public class childClass : ParentClass
{
}

You have to Create Refferance of Child Class to Acess the Normal(); function .
childClass obj=new childClass();
obj.Normal();

Try something like this;
class ParentClass
{
public int Normal()
{
return 1;
}
}
// Derived class
class ChildClass: ParentClass
{
public int someMethod()
{
return Normal();
}
}

You need to cast the object down.
You do it when you need to apply a child's function to a parent object.
In order to do that, you need to declare you want to cast the object later by using the child constructor when creating the parent, like so:
class foo{}
class goo:foo{ public void DoStuff(){} }
/*.... In the main program ..... */
foo a = new goo(); // Declaring the a, which is of type foo, might be used as a goo later on.
And for useage, cast it down.
((goo)a).DoStuff();
Hope it helps :)

You cannot call a child class method from parent. But can call parent class method from child.
namespace MyProgram
{
public class ParentClass
{
public int Normal()
{
return 1;
}
}
public class childClass : ParentClass
{
Normal(); // which calls the method in Base class(ParentClass)
//base.Normal(); //or this one in which base tells that the method is in base class
}
}

Related

C# Call Base method with another THIS

I have the following method in the base class:
public class Base
{
protected string Make(string param)
{
return this.ClientID + "_" + configParam;
}
}
And i have another class
public class Class2 : Base
{
}
And
public class Class3 : Base
{
//HERE i would like to call Make but with the THIS as Class2, not the current - Class3.
}
Is this possible?
Thanks.
Suppose you want only subclasses of Base to invoke Make, even if it's not their own Make, you can add a protected invoker method (I call it InvokeSiblingMake):
public class Base
{
private string ClientID;
protected string Make(string param)
{
return this.ClientID + "_" + param;
}
protected void InvokeSiblingMake(Base other)
{
other.Make("hello world");
}
}
public class Class2 : Base
{
}
public class Class3 : Base
{
//HERE i would like to call Make but with the THIS as Class2, not the current - Class3.
public void Test(Class2 other)
{
InvokeSiblingMake(other);
}
}
With the structure of the classes that you have Class3 is a sibling of Class2. You inherit from your parents, not your brother and sister. This means there is no way to cleanly call a method on Class2 from within Class3 through means of base.
There are ways around that by giving a Class2 member variable to Class3, however at that point you're not using inheritance. In that approach, Class2 could inherit from System.Object, System.DateTime or any other class you may create yourself. Then you're acting on the object set as the property, and not through inheritance.

How to Get Base Class Instance from a Derived Class

I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.
Example Code
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
If you're working with an instance of the derived class, there is no base instance.
An example:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
What is not possible within B:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
You can do something like this:
public void Bar()
{
base.Foo();
}
And you can add another method like
public A GetBase()
{
return (A)this;
}
And then you can
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
So this GetBase() method is probably what you want.
The punchline is: If you have an instance of B, it inherits all properties and the non-overriden behaviour of A, but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A. You can cast your B instance to A, but it remains to be an instance of B.
Well you not provide code for your question, but i supsect you want something like
class Base
{
public virtual void Foo()
{
Console.WriteLine("base");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("derived");
}
//// bad
//public Base MyBase
//{
// get
// {
// return base; // Use of keyword 'base' is not valid in this context
// }
//}
// work but...
public Base MyBase
{
get
{
return (Base)this;
}
}
}
But keep in mind that MyBase is really of type Derived
new Derived().MyBase.Foo(); // output "derived"
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
public abstract class foo {
public virtual void bar(){..}
}
public class footwo : foo {
public override void bar(){
// do somethng else OR:
return base.bar();
}
}
}
The derived instance IS the base instance. It's just one object instance in memory.
example:
public class A : B
{
}
var thing = new A();
thing is an instance of an A, and is also an instance of a B.
You could for example, write this line:
B thing2 = thing;
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.
// Create a "Parent" class that has some attributes.
public class Parent
{
public string attribute_one { get; set; }
public string attribute_two { get; set; }
public string attribute_three { get; set; }
}
// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
public string attribute_four { get; set; }
public string attribute_five { get; set; }
public string attribute_six { get; set; }
}
// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
attribute_one = "interesting";
attribute_two = "strings";
attribute_three = "to";
attribute_four = "put";
attribute_five = "all";
attribute_six = "together";
};
// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();
// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
// Set the values in the base class using the ones
// that were set in the derived class above.
property.SetValue(parent, property.GetValue(child));
}
The result is a new object populated with the base class properties of the child class.
class Parent
{
private Parent _parent;
public Parent()
{
_parent = this;
}
protected Parent GetParent()
{
return _parent;
}
}
class Child : Parent
{
private Parent _parent;
public Child()
{
_parent = base.GetParent();
}
}

Cannot access a non-static member of outer type via nested type

I have error
Cannot access a non-static member of outer type 'Project.Neuro' via
nested type 'Project.Neuro.Net'
with code like this (simplified):
class Neuro
{
public class Net
{
public void SomeMethod()
{
int x = OtherMethod(); // error is here
}
}
public int OtherMethod() // its outside Neuro.Net class
{
return 123;
}
}
I can move problematic method to Neuro.Net class, but I need this method outside.
Im kind of objective programming newbie.
Thanks in advance.
The problem is that nested classes are not derived classes, so the methods in the outer class are not inherited.
Some options are
Make the method static:
class Neuro
{
public class Net
{
public void SomeMethod()
{
int x = Neuro.OtherMethod();
}
}
public static int OtherMethod()
{
return 123;
}
}
Use inheritance instead of nesting classes:
public class Neuro // Neuro has to be public in order to have a public class inherit from it.
{
public static int OtherMethod()
{
return 123;
}
}
public class Net : Neuro
{
public void SomeMethod()
{
int x = OtherMethod();
}
}
Create an instance of Neuro:
class Neuro
{
public class Net
{
public void SomeMethod()
{
Neuro n = new Neuro();
int x = n.OtherMethod();
}
}
public int OtherMethod()
{
return 123;
}
}
you need to instantiate an object of type Neuro somewhere in your code and call OtherMethod on it, since OtherMethod is not a static method. Whether you create this object inside of SomeMethod, or pass it as an argument to it is up to you. Something like:
// somewhere in the code
var neuroObject = new Neuro();
// inside SomeMethod()
int x = neuroObject.OtherMethod();
alternatively, you can make OtherMethod static, which will allow you to call it from SomeMethod as you currently are.
Even though class is nested within another class, it is still not obvious which instance of outer class talks to which instance of inner class. I could create an instance of inner class and pass it to the another instance of outer class.
Therefore, you need specific instance to call this OtherMethod().
You can pass the instance on creation:
class Neuro
{
public class Net
{
private Neuro _parent;
public Net(Neuro parent)
{
_parent = parent;
}
public void SomeMethod()
{
_parent.OtherMethod();
}
}
public int OtherMethod()
{
return 123;
}
}
I think making an instance of outer class in inner class is not a good option because you may executing business logic on outer class constructor. Making static methods or properties is better option. If you insist making an instance of outer class than you should add another parameter to outer class contructor that not to execute business logic.

C# possible to have a constructor in an abstract class?

I have 1 abstract class that is calling a static method which up until now didn't require any parameters. This has recently changed. In reality the static method exists in another class and sets the value of BaseMessageDirectory, but in this example below I have simplified things...
So now I want to create my derived classes in such a way that they can initialize some required properties in the parent class during the inheritance, is this possible?
For example....
public abstract class ParentClass
{
protected string BaseMessageDirectory;
protected ParentClass(EnumOperationType operationType)
{
if(operationtype == 1)
{
BaseMessageDirectory = "one";
}
else
{
BaseMessageDirectory = "two";
}
}
}
Yes, you can define a constructor, and all child classes will have to call it:
public class Child : ParentClass
{
public Child() : base(EnumOperationType.One) { ... }
}

Creating an object of the type a static method is called on in an inheritance chain in C#

I am trying to do something like this in C#
public class ParentClass {
public static ParentClass GetSomething()
{
var thing = new // ?????
return thing;
}
}
public class ChildClass : ParentClass {
}
And then I want to be able to call the static method on the child class like so:
ChildClass blah = ChildClass.GetSomething();
e.g. When calling the static method on the child class I want to instantiate an instance of the child class. But I just want the static method defined on the parent. Is this at all possible? I'd be happy even with:
ChildClass blah = (ChildClass) ChildClass.GetSomething();
Thanks!
This smells awful, but you could do this:
public class ParentClass {
public static T GetSomething<T>() where T : ParentClass, new() {
return new T();
}
}
Usage:
ParentClass parent = ParentClass.GetSomething<ParentClass>();
ChildClass child = ChildClass.GetSomething<ChildClass>();
This is legit too:
ParentClass parent = ChildClass.GetSomething<ParentClass>();
which contributes to the smelliness of this (yes it just compiles to ParentClass parent = ParentClass.GetSomething<ParentClass>() but it still smells).
You cannot 'override' static methods. But you can use generics to tell the ParentClass which derived class you actually means. It's somewhat ugly but it works:
class ParentClass<T> where T : ParentClass<T>, new()
{
public static T GetSomething()
{
T thing = new T();
return thing;
}
}
class ChildClass : ParentClass<ChildClass>
{
}
Test:
ChildClass x = ChildClass.GetSomething(); // works
This line:
ChildClass blah = ChildClass.GetSomething();
is compiled to exactly the same IL as this line:
ChildClass blah = ParentClass.GetSomething();
(when ChildClass doesn't declare its own GetSomething method).
I would prefer:
ChildClass blah = ParentClass.GetSomething<ChildClass>();
It's like your casting version, but with angle brackets and the type name coming after instead of before the method name :) (Basically Jason's suggestion, now I've seen it!)
However, this is now somewhat independent of ParentClass - you can define it anywhere that's useful:
public static class FactoryUtil
{
public static T CreateInstance<T>() where T : ParentClass
{
...
}
}
... or you could provide a factory as a dependency where you need it, making things more testable, potentially...
C# doesn't let you override static methods.
There's nothing stopping you, though, from redefining a new static method on ChildClass that hides the ParentClass method. Would doing that help?

Categories