I'm writing a base validator class, let's call it abstract BaseFoo.
I'm also writing two implementation classes, let's call them Bar and
Quux. I want them all to share a static field that defines a regular
expression pattern used in the validation. I fail to understand why,
logically, this cannot be so. (I'm entirely willing to accept (albeit
rather frustrated) that C# just doesn't allow it, it's the *rationale*
I'm having trouble getting my head round.)
Why can I not have something like:
public abstract class BaseFoo
{
public static abstract string MatchPattern { get; }
}
public class Bar : BaseFoo
{
public static override string MatchPattern { get { ... } }
}
etc?
I read a post on a Java forum[1] that almost got my head around it,
but now I no longer follow.
Sure, the static member in the abstract class would belong to that
class and not to the derived classes. But if it's abstract (rather
than virtual, though I think the logic would still stand for static
virtual members), what difference does it make?
Surely it makes more sense, in my example, for the MatchPattern --
which will not vary between instances of the Bar and Quux
implementations -- to be static, rather than to have to declare an
instance of Bar in order to reference its match pattern?
Anyone got any explanations that will make it all make sense to me?
Anyone got any cunning ploys that will allow me to have what is
effectively an abstract static member (and overridden static members
in the derived classes)?
All responses gratefully received,
Owen Blacker,
Technical Team Lead
--
[1] http://forum.java.sun.com/thread.jspa?threadID=597378
You can do something like:
public abstract class BaseFoo
{
public static string MatchPattern { get { return ""; } }
}
public class Bar : BaseFoo
{
public static new string MatchPattern
{
get { return "[A-Za-z0-9]+"; }
}
}
It's not like you have an object that you can cast to a base class in this
instance. Virtual/abstract/override are for instance members, and static
properties aren't instances. You have to know the name of the class to access
the property.
At least, that's my understanding of it.
Chris.
Heres two post i found online.. that makes sense to me..
--------
An abstract method requires implementation per instance. Static
methods pertain to an overall class. A static method in an abstract
class belongs to the abstract class, not potential implementations. It
therefore doesn't make any sense to allow abstract static methods.
Furthermore, static methods cannot be overridden, so again, abstract
static methods would be an anomaly.
----------
You can not override a static method; therefore, you could never
implement a static abstract method.
Heres some thing i found online..
1)
An abstract method requires implementation per instance. Static
methods pertain to an overall class. A static method in an abstract
class belongs to the abstract class, not potential implementations. It
therefore doesn't make any sense to allow abstract static methods.
Furthermore, static methods cannot be overridden, so again, abstract
static methods would be an anomaly.
2)
This is the third time i am trying to post to this group.. I was
trying to copy paste something i foudn on the internet...
let me type it in my own words..
Static method belongs to the the class... and NOT to potential derived
classes.....so you will not be able to override it..
> Ok, dumb question, I know, but I just can't get my head round it.
Well, the short answer is that you can't have overridable static members,
because there would be no point in doing so. For static members, there's
no way to refer to a derived class except by referring to the derived
class explicitly, and in that case you have direct access to the member.
Since overridable members essentially allow access to derived members via
the base class, and since for a static member you would never access a
derived member via the base class (since you always have to specify the
type explicitly), there'd be no point.
For more details:
> I'm writing a base validator class, let's call it abstract BaseFoo.
> I'm also writing two implementation classes, let's call them Bar and
> Quux. I want them all to share a static field that defines a regular
> expression pattern used in the validation. I fail to understand why,
> logically, this cannot be so. (I'm entirely willing to accept (albeit
> rather frustrated) that C# just doesn't allow it, it's the *rationale*
> I'm having trouble getting my head round.)
>
> Why can I not have something like:
>
> public abstract class BaseFoo
> {
> public static abstract string MatchPattern { get; }
> }
>
> public class Bar : BaseFoo
> {
> public static override string MatchPattern { get { ... } }
> }
>
> etc?
How would you use the property? When you use static members, you provide
the name of the class, not an instance.
There are really two approaches to the question. One involves how
abstract/virtual members are implemented, and the other involves how they
are used.
From the implementation point of view, the issue is that an overridable
member (i.e. abstract or virtual) requires an instance to carry the type
information required to figure out which version should be used.
If you have a base class B with virtual method Foo() and a derived class D
that overrides that method, then you can treat an instance of D as if it
were an instance of B, and yet still get the implementation from D.
For example:
class B
{
virtual void Foo() { Console.WriteLine("B.Foo"); }
}
class D
{
virtual void Foo() { Console.WriteLine("D.Foo"); }
}
then in some code:
B b = new D();
b.Foo();
outputs:
D.Foo
The way this works is that there's a table of sorts (sometimes referred to
as a "v-table") that's initialized with the instance, and is used when
calling virtual members of the class. A specific entry in the table
corresponds to that method, and callers of the method use the table to
figure out which method to call. Both B and D have essentially the same
table, and the entry in that table for the method Foo() is the same offset
in the table. But instances of B will have a pointer to the
implementation from B and instances of D will have a point to the
implementation from D.
But that data has to live somewhere in the instance. Without an instance,
there's no place to keep the table, and thus no way to allow a method to
be virtual. Static methods are called without instances, and
again...without that instance to provide the table, there's no way to
figure out which method should be called.
Now, another way to look at it is from the point of view of using an
overridable member.
The whole point of an overridable member is so that you can ignore the
actual type of the instance, paying attention to only those things defined
in the base class, and yet still enjoy customized behavior from the
derived class. There are lots of examples of this, so I won't belabor
that point. If you don't understand _why_ overridable members are useful,
you need to revisit that first before you're going to understand why they
don't make sense for static classes.
So, let's assume you understand the above. Then, what point would there
be in a static member that's overridable? You never have an instance when
using a static member. You're always just declaring the implementation,
via the class, explicitly. A static member lives in the class, so to
speak, not in instances of the class. Since the static member you're
using can only be referred to by directly stating the implementation you
want, making it overridable would have no purpose.
> [...]
> Surely it makes more sense, in my example, for the MatchPattern --
> which will not vary between instances of the Bar and Quux
> implementations -- to be static, rather than to have to declare an
> instance of Bar in order to reference its match pattern?
It does make sense for it to be static. It doesn't make any sense for it
to be overridable. The only time you can access it is when you know
exactly what class you're dealing with, explicitly. So you can always
just explicitly state the implementation you want.
If the discussion above doesn't help, then one other thing you might try
doing is write some code that would use a static overridable member as you
think might be useful. Hopefully you'll see immediately why it's not, but
if that doesn't happen, post the code here so that we have something more
specific to talk about. Feel free to start with the MatchPattern property
example you started with.
> [...]
> Anyone got any cunning ploys that will allow me to have what is
> effectively an abstract static member (and overridden static members
> in the derived classes)?
If you can demonstrate what you're trying to accomplish, surely we can
show you how to do it. :) So far, you haven't posted anything that would
actually take advantage of an overridable static member.
Pete
> Ok, dumb question, I know, but I just can't get my head round it.
>
> I'm writing a base validator class, let's call it abstract BaseFoo.
> I'm also writing two implementation classes, let's call them Bar and
> Quux. I want them all to share a static field that defines a regular
> expression pattern used in the validation. I fail to understand why,
> logically, this cannot be so. (I'm entirely willing to accept (albeit
> rather frustrated) that C# just doesn't allow it, it's the *rationale*
> I'm having trouble getting my head round.)
Something that is static just exists once.
If you could override or derive it, you would create it for
a second time.
See it like this:
Something that is not static, be it field, method or
class, serves as a template to create objects from
on runtime that are a 1:1 copy of this template.
Each instance of class Foo with method void Bar() has
its own void Bar() method in terms of memory and address.
A static member is not such a template but already the
real thing in terms of memory and address. It is not
cloned when the instance is being constructed.
I think that's basically the explanation why overriding or
deriving or abstracting static things would make them no longer
static.
MfG,
Alex
Regards,
Jeff
*** Sent via Developersdex http://www.developersdex.com ***
Only using a private constructor and nested subclasses - and at that
point you've got a fairly odd singleton anyway.
If you have a non-private constructor, there's just no way of
preventing (in a compile-time safe way) multiple instances from being
created.
The point of a singleton is to guarantee a single instance. If I
create a subclass, I can expose the constructor publicly, losing all
normal singleton guarantees. Sure, you can put something in the base
constructor to throw an exception if a second instance is created -
but that feels like a code smell to me.
Jon
public abstract class BaseFoo
{
public static abstract string MatchPattern { get; }
}
public class Bar : BaseFoo
{
public static override string MatchPattern { get { ... } }
}
It seems to me it is possible to use instance methods and make class Bar
a Singleton.
Bar could indeed be a singleton - but BaseFoo couldn't be.
Apologies if I misunderstood your original statement, but when you
said: "The singleton pattern does allow subclassing" I inferred that
you meant the singleton class itself can be subclassed, which it
can't. Heck, *every* singleton class is a subclass, if only of
System.Object.
On the other hand, I'm not sure that the singleton pattern really
answers the OP's problem - there's no indication that he actually
wants the class to be a singleton.
Jon
Regards,
Jeff
>>On the other hand, I'm not sure that the singleton pattern really
answers the OP's problem - there's no indication that he actually
wants the class to be a singleton<<
*** Sent via Developersdex http://www.developersdex.com ***
If this method were the only thing the type was going to be used for,
that would be true - but I see no reason to assume that the OP doesn't
actually want to create instances of this type and use them as normal.
There may well be things other than the match pattern which vary
between different instances of the validator.
If the OP really wasn't ever planning on creating any instances, then
using a singleton pattern would indeed be a reasonable solution.
Jon
It is an error to declare a static method abstract or virtual.
Declaring a static method abstract prohibits instantiation of the
enclosing class. Since static methods are part of the class itself they
can be invoked without creating an instance of the class, so there is no
logic in prohibiting instantiation of the enclosing class. Declaring a
static method virtual is an error since it would result in runtime
ambiguity. If the static virtual method was overridden in more than one
subclass, the runtime would not be able to determine which
implementation to invoke.
http://www.geocities.com/jeff_louie/OOP/oop40.htm
Regards,
Jeff
namespace ConsoleApplication1
{
abstract class Class1
{
public abstract static int val
{
get;
}
public static void test1()
{
Console.WriteLine(val);
}
}
class Class2 : Class1
{
public static override int val
{
get { return 10; }
}
}
class Program
{
static void Main(string[] args)
{
Class2.test1();
> I've read this topic, but is still don't know what to do.
> I would like my code to be as following, but gets an error due to
> subject. Is there any way arround this problem, I would really like to
> keep the methode test1 in the super class1, since it's quit complex, but
> need the methode to use the value val depending on the subclass class2.
It simply makes no sense for a static member to be virtual.
In the code example you've provided, the most obvious solution I see is to
make the method "test1()" take a parameter, then provide a different
"call_test1()" method in each class that calls "test1()" with the
appropriate value. That way, each class has its own public version of the
method appropriate to the value in the class, but they both can use the
common implementation in the base class.
There are other approaches that might also work, but as Peter M. notes,
without a more clear higher-level description of what you're really trying
to do, it's hard to provide suggestions.
Pete
> It simply makes no sense for a static member to be virtual.
Actually, it can make sense, though you'd probably want to use a
different name. C# conflates two concepts into one with its static
construct: (1) the visibility of the member - available on the type, not
requiring an instance and (2) the binding of the member, being based on
the static, compile-time type.
For example, consider this scenario:
---8<---
class A
{
public virtual string TypeName
{
get { return "A"; }
}
public override string ToString()
{
return string.Format("I'm a {0} thing", TypeName);
}
}
class B
{
public override string TypeName
{
get { return "B"; }
}
}
--->8---
Here, we are using instance virtual methods in order to get
polymorphism, but the fact that TypeName is a virtual member doesn't
mean that it needs to be an instance member. It doesn't access any
instance members. What would be wrong with wanting to access
"B.TypeName"?
-- Barry
> Peter Duniho wrote:
>
>> It simply makes no sense for a static member to be virtual.
>
> Actually, it can make sense,
No, not in C# it doesn't.
> [...]
> Here, we are using instance virtual methods in order to get
> polymorphism, but the fact that TypeName is a virtual member doesn't
> mean that it needs to be an instance member. It doesn't access any
> instance members. What would be wrong with wanting to access
> "B.TypeName"?
I don't understand the question. You _can_ access "B.TypeName". But you
could only ever do so by using the actual type. There is no scenario in
which the "TypeName" identifier would resolve to "B.TypeName" but where
the class "B" isn't known.
Pete
> On Fri, 16 May 2008 13:33:41 -0700, Barry Kelly <barry....@gmail.com>
> wrote:
>
> > Peter Duniho wrote:
> >
> >> It simply makes no sense for a static member to be virtual.
> >
> > Actually, it can make sense,
>
> No, not in C# it doesn't.
Sure, but I wasn't limiting my point to C#.
It's like an instance of the Sapir-Whorf hypothesis. If C#/Java/C++ are
the only kinds of languages you're[1] familiar with, then a "virtual
static members are nonsensical" may seem like a true statement in
general for object-oriented languages.
[1] I don't mean you specifically, but a generalized third party who may
be reading this and get the wrong idea.
>> >> It simply makes no sense for a static member to be virtual.
>> >
>> > Actually, it can make sense,
>>
>> No, not in C# it doesn't.
>
> Sure, but I wasn't limiting my point to C#.
Why not? I was. This is a C# newsgroup.
There are other languages in which a type identifier is itself treatable
as an object. As an example, in Objective-C, there are class messages and
instance messages, and you can override either. I've been told that
Smalltalk is similar. No doubt lots of other languages are similar, in
that the type identifier is the type itself, rather than being a way to
use the type.
But this is C#. We're talking about C#, where the type identifier is a
different entity than the type itself. Saying "what could be" doesn't
help anyone trying to write C# code.
At the very least, if you're going to diverge from the topic, I think you
should be more explicit about your comments. Someone reading your post
might be misled into thinking that virtual static members "actually...can
make sense" even in C#.
Pete
You can even do it on .NET with Delphi, where "class methods" can be
overridden (including constructors). That's a handy feature, and it's
a shame Anders left it out of C#.
Jesse