...

View Full Version : C# - How do I overwrite a parent method?



bobleny
07-16-2009, 11:12 AM
Hey, anyone here familiar with C#?

I have a parent child class much like this:

Parent class


namespace zzz
{
public abstract class Parent
{
public Parent()
{
// Stuff
}

public string Print()
{
return "Words";
}
}
}


Child class


namespace zzz
{
public class Child : Parent
{
public Child()
{
// Stuff
}

public string Print()
{
return "Different Words";
}
}
}


Main class


namespace zzz
{
public Testy
{
public static void main()
{
Child name = new Child();

Console.WriteLine(Child.Print() + "\n");
}
}
}


The output of the writeline is "Words". How do I get it to output "Different Words?"

Brandoe85
07-16-2009, 04:10 PM
Docs on override have a very basic example that should tip you in the right direction:
http://msdn.microsoft.com/en-us/library/ebca9ah3%28VS.71%29.aspx

bobleny
07-16-2009, 09:54 PM
Thanks! I just needed to "override" the method. I tried looking for a solution online but couldn't find anything. knowing that it is called overriding a method would have helped!

Thanks again.

scottk
07-17-2009, 02:15 PM
Methods you intend to override in a base class should be marked as virtual. You can also override non-virtual methods by using the "new" operator in the method signature of the derived class and calling the base class. Also notice how I called base() on the derived class' constructor. Here are two ways to override:

Method 1


public abstract class Parent
{
public Parent()
{
}
public virtual void Print()
{
//Do stuff
}
}
public sealed class Child : Parent
{
public Child()
: base()
{

}
public override void Print()
{
base.Print();
}
}


Method 2:


public abstract class Parent2
{
public Parent2()
{
}
public void Print()
{
//Do stuff
}
}
public sealed class Child2 : Parent2
{
public Child2()
: base()
{

}
public new void Print()
{
base.Print();
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum