473,769 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Possible to override static member in base class?

It looks like the language is trying to prevent me from doing this sort of
thing. Nevertheless, the following compiles, and I'd like to know why it
doesn't work the way it should:

public class ComponentA
{
static string s_name = "I am the root class.";
public string Name { get {return s_name;} }
}

public class ComponentB : ComponentA
{
new static string s_name = "I am a derived class.";
}

static void Main()
{
ComponentB b = new ComponentB();
Console.WriteLi ne("ComponentB says: " + b.Name);
}

I want this to say "I am a derived class." but it still says "I am the root
class."

My objective is to derive a whole bunch of classes on which I can get a
description both
- Through reflection of the class Type (thus requiring the static member)
- Through an instance of the class using a (virtual) member that is defined
in the root class.

Is this possible?
Jun 16 '06 #1
14 33288
>My objective is to derive a whole bunch of classes on which I can get a
description both
- Through reflection of the class Type (thus requiring the static member)
- Through an instance of the class using a (virtual) member that is defined
in the root class.

Is this possible?


Why don't you make the Name property virtual and override it in the
derived classes.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jun 16 '06 #2
Hi dbooksta,

Thanks for your post!

Yes, C# does not support static virtual member. This is because: to
implement a virtual member, the complier has to place this member as an
entry in the v-table, which attaches to a class instance. Static member
does not attach to any class instance but attaches to the class itself, so
static member can not be virtual and overrided in child class.

You'd better take Mattias' suggestion to mark "Name" instance property as a
virtual one and override it in inherited class. The code snippet below
demonstrates this:

public class ComponentA
{
static string s_name = "I am the root class.";
public virtual string Name { get {return s_name;} }
}

public class ComponentB : ComponentA
{
new static string s_name = "I am a derived class.";
public override string Name { get {return s_name;} }
}

private void button1_Click(o bject sender, System.EventArg s e)
{
ComponentB b = new ComponentB();
Console.WriteLi ne("ComponentB says: " + b.Name);
}
Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 16 '06 #3
OK, this will work. But just to confirm: Is there no way to define an
interface, abstract, or base class such that it REQUIRES that a particular
static member (say "s_name") be defined or redefined in a derived class?

If so, it seems like a language shortcoming, doesn't it?
""Jeffrey Tan[MSFT]"" wrote:
Hi dbooksta,

Thanks for your post!

Yes, C# does not support static virtual member. This is because: to
implement a virtual member, the complier has to place this member as an
entry in the v-table, which attaches to a class instance. Static member
does not attach to any class instance but attaches to the class itself, so
static member can not be virtual and overrided in child class.

You'd better take Mattias' suggestion to mark "Name" instance property as a
virtual one and override it in inherited class. The code snippet below
demonstrates this:

public class ComponentA
{
static string s_name = "I am the root class.";
public virtual string Name { get {return s_name;} }
}

public class ComponentB : ComponentA
{
new static string s_name = "I am a derived class.";
public override string Name { get {return s_name;} }
}

private void button1_Click(o bject sender, System.EventArg s e)
{
ComponentB b = new ComponentB();
Console.WriteLi ne("ComponentB says: " + b.Name);
}
Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 16 '06 #4
Hi dbooksta,

Thanks for your feedback!

No, you can redefine the static member in the child class with "new"
keyword in C#. This will hide the parent class's static member in the child
class. Since C# does not allow us to use class reference to refer the
static member. The correct way of using the redefined static member is
using the child class name. Please see the sample code snippet below:
private void Form1_Load(obje ct sender, System.EventArg s e)
{
ComponentB b = new ComponentB();
MessageBox.Show ("ComponentB says: " + ComponentB.s_na me);//you can not use
b.s_name to access the redefined static member, C# compiler prohibits this
way.
}

public class ComponentA
{
public static string s_name = "I am the root class.";
public string Name { get {return s_name;} }
}

public class ComponentB : ComponentA
{
public new static string s_name = "I am a derived class.";
}

Does this meet your need?

Note: your original sample code result is expected. You did not override
Name property in the child class, then when you are using b.Name to access
"Name" property, you are referring the parent class's "Name" property,
which returns parent class's s_name static member to you. In this scenario,
there is no Polymorphism at all.

Below is some more comment on OOP Polymorphism with static member:

In Object Oriented Programming area, static member is a property of the
class itself, it has nothing to do with any instance of that class.
Polymorphism in OOP means initializing a child class instance and assigning
it to the parent class pointer/reference, like this:
ParentClass obj=new ChildClass();

Then we can override the parent class member behavior in the child class.
This is called Polymorphism in OOP. As we can see, in Polymorphism of OOP,
this concept only applies to the class member, which requires initializing
an instance of the class. This concept does not apply to the class itself.
So Polymorphism concept has nothing to do with static member. Also, neither
C++ nor C# support virtual static member.(Because it does not make sense
based on OOP concept)

Hope this information helps!

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 19 '06 #5
Hi dbooksta,

Does my reply make sense to you? If you still have any concern or
questions, please feel free to tell me, thanks!

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 22 '06 #6
FYI to all, I also realized that I could accomplish my objective here by
tagging my classes with an Inheritable Attribute.
Jun 22 '06 #7
Why do Microsoft employees write messages like this? I mean, they respond to
perhaps 1/1000th of the messages posted here, lard those responses with
useless boilerplate, then write equally useless "followups" like this. It's
like they think newsgroups are email support (except that they ignore most
requests).

Sorry - just had to vent.

///ark

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.com> wrote in message
news:PA******** ******@TK2MSFTN GXA01.phx.gbl.. .
Hi dbooksta,

Does my reply make sense to you? If you still have any concern or
questions, please feel free to tell me, thanks!

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no
rights.

Jun 22 '06 #8
Hi dbooksta,

Thanks for your feedback!

Can you be specific regarding your finding? Please forgive my ignorance,
based on my research, I can not find any "Inheritabl e Attribute" in C#
language specification. Can you share your sample code with us? Thanks :-)

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 23 '06 #9
Basically I define an Attribute like this:

[AttributeUsage( AttributeTarget s.Class, Inherited = true)]
public class ComponentTypeAt tribute : Attribute
{
public string ComponentType;
public ComponentTypeAt tribute(string c)
{
ComponentType = c;
}
}

Now the root class gets:

[ComponentTypeAt tribute("BaseTy pe")]
public class BaseComponent
{
public string ComponentType { get { return
((ComponentType Attribute)Attri bute.GetCustomA ttribute(this.G etType(),
typeof(Componen tTypeAttribute) )).ComponentTyp e; } }
}

A little verbose, but the net effect is that a call to .ComponentType member
of ANY derived class will return "BaseType," unless they redefine the
attribute like this:

[ComponentTypeAt tribute("Specia lType")]
public class Special : BaseComponent {...}

So when we call Special.Type we get "SpecialTyp e"!

Also, we don't have to instantiate any of these classes to find out what
their ComponentType, because the Attribute is defined on the Type.

Hence, we have the effect of a static property that can be both inherited
and overridden!

Jun 29 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1626
by: Bo Sun | last post by:
hi: please take a look at the following code fragment: class Test{ public: static int i; Test() {i = 33;} };
30
3493
by: Joost Ronkes Agerbeek | last post by:
Why is it allowed in C++ to call a static member function of an object through an instance of that object? Is it just convenience? tia, Joost Ronkes Agerbeek
1
3139
by: Tom Regan | last post by:
Is it possible to mark a base class member with XmlTextAttribute and serialize a derived class? When I attempt to do so I get this error: There was an error reflecting type ''. ---> System.InvalidOperationException: Cannot serialize object of type ''. Base type '' has simpleContent and can only be extended by adding XmlAttribute elements. Please consider changing XmlText member of the base class to string array.
1
1896
by: phoenix | last post by:
Hello, I guess I'm missing to logic behind the limitation or I'm doing something wrong (most likely). I have the following interface and class public interface IRBSPParser { void Parser(byte b, int offset, int size) }
3
2963
by: User N | last post by:
Perhaps this is a stupid question, but here goes anyway. Given an instance of an arbitrary class, is it possible to change its base class at runtime? Here's my problem... I need to extend class Foo, which I can't change. Foo holds a reference to a collection of Bar objects and/or objects derived from Bar (which I can't change). My FooExtended class needs to keep extra information for each Bar in that collection. If I could change...
0
1298
by: rain_c1 | last post by:
hi! is there a way to access a static member of a class, if the classname is a variable? this does not work: $classname::$member for methods there is a solution: call_user_func(array($classname, 'method'));
5
2625
by: Dennis Jones | last post by:
Hello, I have a couple of classes that look something like this: class RecordBase { }; class RecordDerived : public RecordBase {
8
1470
by: Diwa | last post by:
In the below example, will d1 and d2 have separate copies of "a" (which is static in base class). Seems like not. If not, then how do I have one static for class d1 and one static for class d2. some_class is populated by "class b" ------------------------------------------------------
5
1737
by: pgrazaitis | last post by:
I cant seem to get my head wrapped around this issue, I have myself so twisted now there maybe no issue! Ok so I designed a class X that has a few members, and for arguments sake one of the members Y is the location of a file to be read. The original design assumes that this class will be instantiated and each instance will happily mange its own members. (ie One file location per instance...no thread-safety). Now another class A...
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.