This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have a Class and Method like below
public class Wakeup : World
{
public void MethodA(string)
{
Log.writeline("Wakeup World");
}
}
And below one is another class and method in which I am trying to call "MethodA"
public class Hello : World
{
public void MethodB()
{
Wakeup p = new Wakeup;
p.MethodA(string);
}
}
This Isn't working. Unable to call "MethodA" inside "MethodB"
Note : Both the classed are Inherited to some other class called "World"
Can anyone suggest me how can I achieve this ?
Create instance of first class inside second one correctly, also pass some string value instead string type in second class method call
public class Wakeup : World
{
public void MethodA(string text)
{
Log.writeline(text);
}
}
public class Hello : World
{
public void MethodB()
{
Wakeup p = new Wakeup();
p.MethodA("Wakeup World");
}
}
You have a typo, you have not placed () at the end of instantiating your Wakeup class. It should be as follow:
Wakeup p = new Wakeup();
Another thing, you should not pass the type itself to the method, in other words do not pass the type word string, but rather a string value. A string value is placed within quotation " " marks, as follow: "Hello, World".
So the following code for you Class Hello should work. Note how I instantiated your Wakeup class, and passed a value to Method A. Here is the complete code:
public class Wakeup : World
{
public void MethodA(string strValue)
{
Console.WriteLine(strValue);
}
}
public class Hello : World
{
public void MethodB()
{
Wakeup p = new Wakeup();
p.MethodA("Hello, World");
}
}
works great for me
public class World { }
public class Wakeup : World
{
public void MethodA(string a)
{
Console.WriteLine("Wakeup World");
}
}
public class Hello : World
{
public void MethodB()
{
Wakeup p = new Wakeup();
p.MethodA("Dsa");
}
}
Related
Here is an example of what I am looking to do.
public class ParentA {}
public class ChildA : ParentA
{
public string x;
}
public class A
{
public virtual void DoSomething(Parent a)
{
// perform something
}
}
public class B : A
{
public Override void DoSomething(Child a)
{
// perform something slightly different using both strings
a.x = "something";
}
}
but turn out I got an error with "No Suitable Method found to Override".
So I want to override DoSomething from class A and pass a different set of child class parameter. Is this possible?
When you override something, the signature of the method has to be the same.
So in your case, you can do something like this
public class Parent { }
public class Child : Parent
{
public string x;
}
public class A
{
public virtual void DoSomething(Parent a)
{
// perform something
}
}
public class B : A
{
public override void DoSomething(Parent a)
{
if (a is Child child)
{
// perform something slightly different using both strings
child.x = "something";
}
}
}
I'm not 100% sure exactly what you're trying to accomplish, however generics may help you:
public class Parent { }
public class Child : Parent
{
public string x;
}
public class A<T> : Parent where T : Parent
{
public virtual void DoSomething(T a)
{
}
}
public class B : A<Child> // Child could also be Parent here
{
public override void DoSomething(Child a)
{
a.x = "test";
}
}
I’m working with a state pattern and are wondering how to define variables so they can use in each child class. A protected variable in the abstract parent class may be the right choice, but with this, I’m wondering how to initialize these variables from the main class.
class Main
{
\\Initialize variable "file" here?
\\...
Context tc = new Context(new Step01());
\\...
}
class Context
{
private State ts;
// Constructor
public Context(State st)
{
this.State = st;
}
// Gets or sets the state
public State State
{
get
{
return st;
}
set
{
st = value;
}
}
public void Request()
{
ts.Handle(this);
}
}
abstract class State
{
protected string file = "file";
public abstract void Handle(Context tc);
}
class Step01 : State
{
tc.State = new Step02();
// use variable "file"
}
class Step02 : State
{
tc.State = new Step0x()
// use variable "file"
}
The example is a code snipped and don't work. I hope it helps to explain my question more accurate.
The quantity of child classes (Step0x) varies, so I think it's easier to define the variable only once in the parent class.
Does anybody have an idea how to initialize my variables in the main class?
Thank you.
Define file as constant:
abstract class State
{
protected const string file = "file";
public abstract void Handle();
}
Here is implementation of Step01 and Step02 which are using file:
class Step01 : State
{
public override void Handle(){}
public void PrintFile()
{
Console.WriteLine(string.Format("step1 + {0}", file));
}
}
class Step02 : State
{
public override void Handle(){}
public void PrintFile()
{
Console.WriteLine(string.Format("step2 + {0}", file));
}
}
And here is usage of the Step01 and Step02 classes:
static void Main(string[] args)
{
Step01 step1 = new Step01();
step1.PrintFile();
Step02 step2 = new Step02();
step2.PrintFile();
Console.ReadLine();
}
I expected output C in this program. But real result is A.
Please, explain why program prints A.
class A
{
public virtual void say()
{
Console.WriteLine ("A");
}
}
class B : A
{
public new virtual void say()
{
Console.WriteLine ("B");
}
}
class C : B
{
public override void say()
{
Console.WriteLine ("C");
}
}
class MainClass
{
public static void Main (string[] args)
{
A a = new C ();
a.say();
}
}
It's because you created new virtual method say() in the class B.
This new method hides original method A.say(), so in the class C you overriden this new method B.say() but not the A.say().
And since you declared your object as A
A a = new C ();
the old A.say() method is called.
You're not overriding the say method in Class B, which is the sub class of Class C.
public new virtual void say()
In the above line, you're hiding the say method. Look at the new modifier here on MSDN
I have a class with functions:
class MyClass
{
public List<Attachment> Attachments;
public void A()
{
// Do something
}
public void B()
{
// Do something
}
}
class AttachmentA : Attachment
{
public void A()
{
// Do something else
RealA();
}
}
class AttachmentB : Attachment
{
public void B()
{
// Do something else
// RealB();
// No need to call base function here
}
}
I need in my code when I attach AttachmentA to MyClass that all the functions in MyClass that are also present in AttachmentA to be overridden by the functions in AttachmentA and also give access to the original functions in MyClass.
For example, I create MyClass and then attach AttachmentA instance to it. calling MyClass.A() will actually call AttachmentA.A() and the AttachmentA.RealA() will call the base function that was overridden.
I know this can be somehow done with something like using event handlers lists to handle overrides but is there an easy way to implement this?
Edit: I have no problem with long code that uses reflection as long as its present once and doesn't have to be even mentioned in any of the functions - maybe only when attaching attachement.
Edit: you wanted an example:
class MyClass
{
public List<Attachment> Attachments;
public MyClass()
{
Attachments = new List<Attachment>();
}
public void Attach(Attachment attachment)
{
Attachments.Add(attachment);
// Do some magic here
}
public void A()
{
Console.WriteLine("MyClass.A");
}
public void B()
{
Console.WriteLine("MyClass.B");
}
}
class AttachmentA : Attachment
{
public void A()
{
Console.WriteLine("AttachmentA.A");
RealA();
}
}
class AttachmentB : Attachment
{
public void B()
{
Console.WriteLine("AttachmentB.B");
}
}
public class Program
{
public static void Main(string[] Args)
{
MyClass aaa = new MyClass();
aaa.A(); // should print MyClass.A
aaa.B(); // should print MyClass.B
aaa.Attach(new AttachmentA());
aaa.Attach(new AttachmentB());
aaa.A(); // should print AttachmentA.A <newline> MyClass.A
aaa.B(); // should print AttachmentB.B
}
}
Edit: What I want to achieve here is like unit with attributes( = attachments). When the unit get an attachment of RandomSpeed, RandomSpeed will override the unit's GetSpeed and return random value. when it will get an attachment of evasion, it will override that units ReduceHP function and sometimes based on random value will not call the base function.
Edit: What will really solve this mess is to somehow use reflection to change virtual method tables, I'm gonna make a followup on a separate question. I keep this question here incase someone find a better way to do this.
As mentioned in comments, Decorator Pattern is what you are looking for.
http://en.wikipedia.org/wiki/Decorator_pattern
The decorator pattern can be used to
make it possible to extend (decorate)
the functionality of a certain object
at runtime, independently of other
instances of the same class, provided
some groundwork is done at design
time. This is achieved by designing a
new decorator class that wraps the
original class.
Why not take another approach? Have attachments implement interfaces based on what they want to override, for example ISpeedAttachment. Then you could, in the base speed function loop through attachments which implement ISpeedAttachment, calling them.
Have the interfaces return null if they haven't taken effect and you could then check they've all returned null and call the base class as appropriate, or pass in a ref parameter which you could adjust as necessary.
You should look into the behavioral patterns. For your particular problem I would recommend either the chain of responsibility or the strategy pattern.
If you don't want to introduce dependencies, like inheritance or interfaces to implement on MyClass then:
You can achieve this through delegates.
Long story short, you cannot override function in runtime without resorting to some obscure reflection magic, but you can declare delegates instead of functions. When you construct your class in the constructor fill the delegates with private methods which will be used for as long as no AttachmentA class comes in. And use those delegates instead of the methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
static class Program
{
static void Main(string[] args)
{
MyClass aaa = new MyClass();
aaa.A(); // should print MyClass.A
aaa.B(); // should print MyClass.B
aaa.Attach(new AttachmentA());
aaa.Attach(new AttachmentB());
aaa.A(); // should print AttachmentA.A <newline> MyClass.A
aaa.B(); // should print AttachmentB.B
}
}
class MyClass
{
public List<Attachment> Attachments;
public MyClass()
{
A = _A;
B = _B;
Attachments = new List<Attachment>();
}
public void Attach(Attachment attachment)
{
Attachments.Add(attachment);
// this is your magic
if (attachment.GetType() == typeof(AttachmentA)) {
A = ((AttachmentA)attachment).A;
}
else if (attachment.GetType() == typeof(AttachmentB))
{
B = ((AttachmentB)attachment).B;
}
}
public delegate void delegateA();
public delegate void delegateB();
public delegateA A;
public delegateB B;
public void _A()
{
Console.WriteLine("MyClass.A");
}
public void _B()
{
Console.WriteLine("MyClass.B");
}
}
class Attachment {
}
class AttachmentA : Attachment
{
public void A()
{
Console.WriteLine("AttachmentA.A");
}
}
class AttachmentB : Attachment
{
public void B()
{
Console.WriteLine("AttachmentB.B");
}
}
}
If you need the execution to start always in MyClass instead of the Attachment class you can wrap the delegates like here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
static class Program
{
static void Main(string[] args)
{
MyClass aaa = new MyClass();
aaa.A(); // should print MyClass.A
aaa.B(); // should print MyClass.B
aaa.Attach(new AttachmentA());
aaa.Attach(new AttachmentB());
aaa.A(); // should print AttachmentA.A <newline> MyClass.A
aaa.B(); // should print AttachmentB.B
}
}
class MyClass
{
public List<Attachment> Attachments;
public MyClass()
{
Attachments = new List<Attachment>();
}
public void Attach(Attachment attachment)
{
Attachments.Add(attachment);
if (attachment.GetType() == typeof(AttachmentA)) {
_A = ((AttachmentA)attachment).A;
}
else if (attachment.GetType() == typeof(AttachmentB))
{
_B = ((AttachmentB)attachment).B;
}
}
public delegate void delegateA();
public delegate void delegateB();
public delegateA _A;
public delegateB _B;
public void A()
{
if (_A != null)
{
_A();
}
else
{
Console.WriteLine("MyClass.A");
}
}
public void B()
{
if (_B != null)
{
_B();
}
else
{
Console.WriteLine("MyClass.B");
}
}
}
class Attachment {
}
class AttachmentA : Attachment
{
public void A()
{
Console.WriteLine("AttachmentA.A");
}
}
class AttachmentB : Attachment
{
public void B()
{
Console.WriteLine("AttachmentB.B");
}
}
}
You can shorten this to one delegate type if A and B have the same parameters and return type in your real scenario.
I'm not sure if dynamically overriding a class's functionality is possible, but you can achieve something similar by using different interfaces. Depending on the context you want to use this in, it may require only small redesign.
The standard way of doing it would be this:
using System;
class MyClass
{
public virtual void A()
{
Console.WriteLine("MyClass.A");
}
public virtual void B()
{
Console.WriteLine("MyClass.B");
}
}
class ClassA : MyClass
{
public override void A()
{
Console.WriteLine("AttachmentA.A");
base.A();
}
}
class ClassB : MyClass
{
public override void B()
{
Console.WriteLine("AttachmentB.B");
}
}
public class Program
{
public static void Main(string[] Args)
{
MyClass aaa = new ClassA();
MyClass bbb = new ClassB();
aaa.A(); // prints MyClass.A
aaa.B(); // prints MyClass.B
(aaa as ClassA).A(); // prints AttachmentA.A
(aaa as ClassA).B(); // prints MyClass.B
bbb.A(); // prints MyClass.A
bbb.B(); // prints MyClass.B
(bbb as ClassB).A(); // prints AttachmentB.A + MyClass.A
(bbb as ClassB).B(); // prints AttachmentB.B
}
}
Here's another example, similar to what blowdart suggested:
interface ICallMe
{
bool A();
bool B();
}
class MyClass
{
public ICallMe Attachment { get; set; }
public void A()
{
bool BaseFunction = true;
if (Attachment != null)
BaseFunction = Attachment.A();
if (BaseFunction)
Console.WriteLine("MyClass.A");
}
public void B()
{
bool BaseFunction = true;
if (Attachment != null)
BaseFunction = Attachment.B();
if (BaseFunction)
Console.WriteLine("MyClass.B");
}
}
class ClassA : ICallMe
{
public bool A()
{
Console.WriteLine("AttachmentA.A");
return true;
}
public bool B()
{
Console.WriteLine("AttachmentA.B");
return false;
}
}
static class Program
{
static void Main(string[] args)
{
MyClass aaa = new MyClass();
aaa.A(); // prints MyClass.A
aaa.B(); // prints MyClass.B
aaa.Attachment = new ClassA();
aaa.A(); // should print AttachmentA.A <newline> MyClass.A
aaa.B(); // should print AttachmentB.B
}
}
This only allows for a single attachment to be added. If you wanted to override the behavior of several functions separately, you could use a Collection of some sort to hold the attachments. Within the base class you'd need to loop through them and find the one you want to execute.
I want to create a class that can only be inherited, for that i know it should be made abstract. But now the problem is that i want to use functions of that class without making them static. How can i do that.
public abstract Class A
{
A()
{}
public void display()
{}
}
public Class B:A
{
base.A() // this is accessible
this.display() // this is not accessible if i dont make this function static above
}
Your example will not compile, you could consider something like this:
using System;
public abstract class A
{
protected A()
{
Console.WriteLine("Constructor A() called");
}
public void Display()
{
Console.WriteLine("A.Display() called");
}
}
public class B:A
{
public void UseDisplay()
{
Display();
}
}
public class Program
{
static void Main()
{
B b = new B();
b.UseDisplay();
Console.ReadLine();
}
}
Output:
Constructor A() called
A.Display() called
Note: Creating a new B() implicitly calls A(); I had to make the constructor of A protected to prevent this error:
"'A.A()' is inaccessible due to its protection level"
That's not true. You don't have to make Display() static; you can call it freely from the subclass. On the other hand, you can't call the constructor like that.
Maybe it's just an error in the example, but the real issue with the code you have is that you can't put method calls in the middle of your class definition.
Try this:
public abstract class A
{
public void Display(){}
}
public class B:A
{
public void SomethingThatCallsDisplay()
{
Display();
}
}
Here's how you can do this..
public abstract class A
{
public virtual void display() { }
}
public class B : A
{
public override void display()
{
base.display();
}
public void someothermethod()
{
this.display();
}
}