Overriding parent field values with child ones

P

Pavils Jurjans

Hello,

Please see the following code:

using System;

public class Parent
{
public virtual string id = "_";
public string getId()
{
return id;
}
}
public class Child : Parent
{
public override string id = "A";
}

public class Executer
{
public static void Main()
{
Parent p = new Child();
Console.Write(p.getId());
}
}


Of course, this doesn't compile. But, is there some way to override parent
class field values with child ones, just like it is possible with
virtual/override on methods? Currently I see that I can create a "getId"
method for every child class, but that seems to be quite clumsy method.

Thanks,

-- Pavils
 
J

Jon Skeet [C# MVP]

Pavils Jurjans said:
Of course, this doesn't compile. But, is there some way to override parent
class field values with child ones, just like it is possible with
virtual/override on methods? Currently I see that I can create a "getId"
method for every child class, but that seems to be quite clumsy method.

You can't "override" fields, but you can set values from the child
class. I wouldn't suggest using a public field, but you could use a
private field and a protected method which set the field. Your Child
class could then have a call to SetID (or whatever) in its constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top