473,325 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Inheritable Static methods

Hi,

Is there any way to make this method inheritable and have it behave
appropriately on inherited classes? Using generics? Extension methods?
Something else?

class baseClass
{
public static string ClassName()
{
return typeof(baseClass).FullName;
}
}

what I want is for:

class someClass : baseClass
{
....
}

and to be able to call someClass.ClassName() and have it return
"someClass"

obviously I can manually reimplement ClassName() in every inherited
subclass, but it strikes me that there should be -some- way of adding
a static method to a class that returns its own type name, without
having to do it manually for every inherited subclass.

-regards,
Dave

Jun 27 '08 #1
14 1612
d-42 wrote:
Is there any way to make this method inheritable and have it behave
appropriately on inherited classes? Using generics? Extension methods?
Something else?

class baseClass
{
public static string ClassName()
{
return typeof(baseClass).FullName;
}
}

what I want is for:

class someClass : baseClass
{
...
}

and to be able to call someClass.ClassName() and have it return
"someClass"

obviously I can manually reimplement ClassName() in every inherited
subclass, but it strikes me that there should be -some- way of adding
a static method to a class that returns its own type name, without
having to do it manually for every inherited subclass.
Why is:

someClass.ClassName()

better than:

typeof(someClass).FullName

?

Arne
Jun 27 '08 #2
d-42 <db********@gmail.comwrote:
Is there any way to make this method inheritable and have it behave
appropriately on inherited classes? Using generics? Extension methods?
Something else?
No - the "static" part really means "resolved at compile-time". There's
no such thing as a virtual "per type rather than per instance" member
in C# (although such things exist on other systems).
class baseClass
{
public static string ClassName()
{
return typeof(baseClass).FullName;
}
}

what I want is for:

class someClass : baseClass
{
...
}

and to be able to call someClass.ClassName() and have it return
"someClass"

obviously I can manually reimplement ClassName() in every inherited
subclass, but it strikes me that there should be -some- way of adding
a static method to a class that returns its own type name, without
having to do it manually for every inherited subclass.
When you write someClass.ClassName(), the compiler will replace it with
baseClass.ClassName() in the generated IL.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #3
On May 26, 3:25 pm, Arne Vajhøj <a...@vajhoej.dkwrote:
d-42 wrote:
Is there any way to make this method inheritable and have it behave
appropriately on inherited classes? Using generics? Extension methods?
Something else?
class baseClass
{
public static string ClassName()
{
return typeof(baseClass).FullName;
}
}
what I want is for:
class someClass : baseClass
{
...
}
and to be able to call someClass.ClassName() and have it return
"someClass"
obviously I can manually reimplement ClassName() in every inherited
subclass, but it strikes me that there should be -some- way of adding
a static method to a class that returns its own type name, without
having to do it manually for every inherited subclass.

Why is:

someClass.ClassName()

better than:

typeof(someClass).FullName

?
encapsulation
elegance

I want this class hierarchy to provide its class name as part of its
static 'API' because a number of its methods take those class names
as inputs.

-cheers,
Dave
Jun 27 '08 #4
On May 26, 3:32 pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
d-42 <db.pors...@gmail.comwrote:
Is there any way to make this method inheritable and have it behave
appropriately on inherited classes? Using generics? Extension methods?
Something else?

No - the "static" part really means "resolved at compile-time". There's
no such thing as a virtual "per type rather than per instance" member
in C# (although such things exist on other systems).
I realize i used the word 'virtual' but I'm only describing the sort
of 'behaviour' I'm talking about. In practice, what I'm asking for
does fall within 'static' resolved at compile-time usage.

The usage is that: someClass.FullName() would be written in the code,
their is no compile time ambiguity what someClass is, its the name of
the type 'someClass'.

And as I said, I could easily, but tediously, write:

static public override string FullName()
{
return typeof(CLASS-NAME-GOES-HERE).FullName;
}
or even simply:
static public override string fullName()
{
return "CLASS-NAME-GOES-HERE";
}

And either would actually meet my need. I just wanted to avoid writing
all these essentially identical methods manually for every subclass in
the hierarchy, and for future subclasses.

Given all these functions all follow an identical format, it seemed
reasonable to imagine that a generic method template could generate
the methods for me.
When you write someClass.ClassName(), the compiler will replace it with
baseClass.ClassName() in the generated IL.
Yes, clearly 'virtual' members aren't going to work here, as they need
an runtime instance.... but I was thinking maybe a generic template
construction or an extension method... something sort of like:

static public string <T>.ClassName() { return typeof(T).FullName;}

Then at compile time, upon seeing someClass.ClassName() the compiler
would not find any pre-defined matches, match it to the template and
generate on the fly:

public string someClass.ClassName() { return
typeof(someClass).FullName;}

and use that. Except of course that doesn't appear to be allowed.

regards,
Dave
Jun 27 '08 #5
On Mon, 26 May 2008 16:15:41 -0700, d-42 <db********@gmail.comwrote:
>Why is:

someClass.ClassName()

better than:

typeof(someClass).FullName

?

encapsulation
elegance
In what way would those goals be served?
I want this class hierarchy to provide its class name as part of its
static 'API' because a number of its methods take those class names
as inputs.
Can you provide an example of when you believe you would use this?

What you're talking about might make sense in other languages. But in C#,
you're never going to call the "inherited" method without explicitly
providing the type itself. Any static method, even one that meets your
hypothetical goal of being virtual, needs to be called via the type name
itself.

That's the point of Arne's question. Let's assume you _could_ come up
with a static virtual method that does what you want. You would still
only ever be calling this method by providing the type name itself. If
you want the "someClass" implementation, then you'd have to write
"someClass.ClassName()" (or IMHO it'd be a property and you'd write
"someClass.ClassName", but whatever).

How is this significantly better than simply writing
"typeof(someClass).FullName"?

Pete
Jun 27 '08 #6
On May 26, 4:37 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Mon, 26 May 2008 16:15:41 -0700, d-42 <db.pors...@gmail.comwrote:
What you're talking about might make sense in other languages. But in C#,
you're never going to call the "inherited" method without explicitly
providing the type itself. Any static method, even one that meets your
hypothetical goal of being virtual, needs to be called via the type name
itself.
You are absolutely right.

In EVERY usage scenario for this the programmer writing the code
definitelly knows the classname. They could even just enter in the
string itself. The reason for providing it as a property is not
because its unknown, but because its an elegant way of converting the
classname to a string, without hardcoding a string.

For example... any situation where the user might use someClass.Name,
they could just as easily use the string "someClass" directly, never
mind having to use a typeof(someClass).Name.

But I don't believe hard coding the strings is good style. You lose
out on intelli-sense and compile time checking. Its also easier to
propagate changes to the class name to dependant code if the class
name isn't hard coded in strings all over the place.

Using typeof(someClass).Name works just fine, benefits from
intellisense, and compile type checking, etc... so it meets those
requirements.

But if its something I need a lot of why wouldn't I want to
encapsulate it into the class itself, so that instead of having the
user of the class reflect its name to a string whenever they need it,
the class provides a method or property that does it.
That's the point of Arne's question. Let's assume you _could_ come up
with a static virtual method that does what you want. You would still
only ever be calling this method by providing the type name itself.
Agreed. Its just about encapsulation and style.
If
you want the "someClass" implementation, then you'd have to write
"someClass.ClassName()" (or IMHO it'd be a property and you'd write
"someClass.ClassName", but whatever).
Agreed. I'd prefer a property to a method.
How is this significantly better than simply writing
"typeof(someClass).FullName"?
That's basically the same as asking:

How is writing myInt.ToString() significantly better than
Convert.ToString(myInt)

Its not that one is 'signficantly better' than the other. The latter
has an external (Convert) class perform the conversion on the int
type, the former encapsulates the conversion into the int type. Two
different ways of doing the same thing. Nothing wrong with either. And
indeed, for all i know myInt.ToString() is implemented as
Convert.ToString(this) behind the scenes.

That's not really the issue.

In this case, because the the class names will be frequently needed it
makes aesthetic sense to have the class provide its own name, rather
than require the programmers to reflect out themselves each time. Just
like it makes sense for Int to be able to convert itself to a string
without the caller manually invoking a helper class each time.

Either will work. It just seems odd that this particular bit of
functionality can't easily be encapsulated.

cheers,
-Dave
Jun 27 '08 #7
On May 27, 12:35 am, d-42 <db.pors...@gmail.comwrote:
I realize i used the word 'virtual' but I'm only describing the sort
of 'behaviour' I'm talking about. In practice, what I'm asking for
does fall within 'static' resolved at compile-time usage.
Well, not really. The exact method to call is resolved at compile-
time, and there *is* only one method to be called - so that method is
indeed called. There's no other context available in C#.
The usage is that: someClass.FullName() would be written in the code,
their is no compile time ambiguity what someClass is, its the name of
the type 'someClass'.
Except that there's no method someClass.FullName(), only
baseClass.FullName() - so that is what's called, and that is what's
resolved at compile-time.

I can see what you want, but there's no way of doing it in C#. I don't
know for sure whether there's any way of doing it in IL, but I doubt
it.
And as I said, I could easily, but tediously, write:

static public override string FullName()
Except you couldn't, because you can only override virtual methods.
You could declare it to be "new" instead though.

<snip>

I'd give up on it, basically - there's no way of doing it in the
current version of C#. Redesign so you don't need it, or live with
using typeof.

Jon
Jun 27 '08 #8
On Mon, 26 May 2008 17:31:14 -0700, d-42 <db********@gmail.comwrote:
[...]
>How is this significantly better than simply writing
"typeof(someClass).FullName"?

That's basically the same as asking:

How is writing myInt.ToString() significantly better than
Convert.ToString(myInt)
And?
Its not that one is 'signficantly better' than the other.
Agreed. At best, you save one function call. For all I know, some
inlining happens, and there's not even that.

That said...
The latter
has an external (Convert) class perform the conversion on the int
type, the former encapsulates the conversion into the int type. Two
different ways of doing the same thing. Nothing wrong with either. And
indeed, for all i know myInt.ToString() is implemented as
Convert.ToString(this) behind the scenes.
It is. Or at least, the docs say so and I trust them.
That's not really the issue.

In this case, because the the class names will be frequently needed it
makes aesthetic sense to have the class provide its own name, rather
than require the programmers to reflect out themselves each time. Just
like it makes sense for Int to be able to convert itself to a string
without the caller manually invoking a helper class each time.
Well, IMHO this is where the comparison breaks down. Even if I thought
calling Convert.ToString() was worse by any metric other than elegance
(certainly not encapsulation), and even if I thought it was so much worse
that it'd be worth debating someone about it, it's not really applicable.

The Convert class really is a different class. But when you use typeof(),
that's not a different class. It's really just a different part -- the
static "instance", if you will -- of your actual class. I admit, writing
"typeof(someClass).FullName" might not look quite as nice as
"someClass.FullName". But really, it's practically the same syntax. Any
difference is surely inconsequential.
Either will work. It just seems odd that this particular bit of
functionality can't easily be encapsulated.
Frankly, your use case here is a bit bizarre IMHO (and I mean that in a
good way :) ). I mean, usually people come here complaining that they
can't have virtual static methods because they want to implement something
that's actually impossible to implement. But here, you've got a perfectly
good alternative syntax that does _exactly_ the same thing.

I don't see the problem.

Pete
Jun 27 '08 #9
On May 26, 11:10 pm, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On May 27, 12:35 am, d-42 <db.pors...@gmail.comwrote:
The usage is that: someClass.FullName() would be written in the code,
their is no compile time ambiguity what someClass is, its the name of
the type 'someClass'.

Except that there's no method someClass.FullName(), only
baseClass.FullName() - so that is what's called, and that is what's
resolved at compile-time.
This is why I thought generics or extension methods or a combination
of the two might hold a solution. Clearly the method would need to be
generated by the compiler from a method template.
I can see what you want, but there's no way of doing it in C#. I don't
know for sure whether there's any way of doing it in IL, but I doubt
it.
I can live with that. What I couldn't live with was not knowing if I
was just missing something. :)

Thanks for your assistance with this.

-cheers,
Dave
Jun 27 '08 #10
On Tue, 27 May 2008 00:49:11 -0700, d-42 <db********@gmail.comwrote:
>Except that there's no method someClass.FullName(), only
baseClass.FullName() - so that is what's called, and that is what's
resolved at compile-time.

This is why I thought generics or extension methods or a combination
of the two might hold a solution. Clearly the method would need to be
generated by the compiler from a method template.
Extension methods require an instance. As for generics, well...surely you
could write a generic method that accomplished what you want, but I can't
see how the resulting syntax could wind up preferable to the existing
"typeof(someClass).FullName" solution. As with a non-generic method to do
the same, the generic method would have to exist in some class, requiring
you to use the name of that class, the name of the method, _and_ the name
of the type in question.

Pete
Jun 27 '08 #11
On May 26, 11:37 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Mon, 26 May 2008 17:31:14 -0700, d-42 <db.pors...@gmail.comwrote:
Frankly, your use case here is a bit bizarre IMHO (and I mean that in a
good way :) ). I mean, usually people come here complaining that they
can't have virtual static methods because they want to implement something
that's actually impossible to implement. But here, you've got a perfectly
good alternative syntax that does _exactly_ the same thing.

I don't see the problem.

Pete
As I replied to Jon Skeet, I can live with using typeof(x).Name. I
would have liked to have made it a simple static property of the class
for aesthetics, but its not really an issue if I can't.

I just wanted to ensure that I truly couldn't do it, and understand
why, because I was surprised to have stumbled into something that
seemed so simple that I couldn't for the life of me figure out how to
do.

Its not often I find myself facing a situation where to get the effect
I want I'd have to write dozens of almost identical functions and not
be able to refactor it.

Thanks for your insights.

-cheers,
Dave
Jun 27 '08 #12
On May 27, 8:57 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
This is why I thought generics or extension methods or a combination
of the two might hold a solution. Clearly the method would need to be
generated by the compiler from a method template.

Extension methods require an instance.
Not quite. They need an expression of the right type, but that
expression can have a null value. As a horrible, horrible example:

using System;
using System.IO;

public static class Extension
{
public static void ShowType<T>(this T foo)
{
Console.WriteLine(typeof(T));
}
}

public class Test
{
static void Main()
{
string x = null;
x.ShowType();

FileStream fs = null;
fs.ShowType();
}
}

I'm not saying this should be d-42's approach, but...

Jon
Jun 27 '08 #13
On May 27, 12:57 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Tue, 27 May 2008 00:49:11 -0700, d-42 <db.pors...@gmail.comwrote:
Except that there's no method someClass.FullName(), only
baseClass.FullName() - so that is what's called, and that is what's
resolved at compile-time.
This is why I thought generics or extension methods or a combination
of the two might hold a solution. Clearly the method would need to be
generated by the compiler from a method template.

Extension methods require an instance.
That's something I learned today. :)
As for generics, well...surely you
could write a generic method that accomplished what you want, but I can't
see how the resulting syntax could wind up preferable to the existing
"typeof(someClass).FullName" solution. As with a non-generic method to do
the same, the generic method would have to exist in some class, requiring
you to use the name of that class, the name of the method, _and_ the name
of the type in question.
Ah, but THAT is precisely the issue extension methods resolve.

After all if I define an extension method:

static public class Util { static public void Print(this string s)
{ Console.Writeline(s);}}

You never see Util when I invoke it. You just see: myString.Print();

So if "static" extension methods could be defined, the extra class
name would be hidden.... of course... we can't so its moot. And even
if we could, I don't think there is any way to pass a "class" as a
parameter.

e.g. if you wanted to define a method:

static void PrintName( ??? x)
{
Console.Writeline(typeof(x).Name);
}

What would the ??? be that would allow you to call:

PrintName(string);

I think the closest I could get would be:

static void PrintName(Type x)
{
Console.Writeline(x.Name);
}

And it would have to be called with:

PrintName(typeof(string));

Is there any way of moving the typeof inside the function, so you can
just call:

PrintName(string);

I don't think you can. Make that two things I learned today. :)

-cheers,
Dave
Jun 27 '08 #14
On Tue, 27 May 2008 01:39:21 -0700, d-42 <db********@gmail.comwrote:
Ah, but THAT is precisely the issue extension methods resolve.
You misphrased that. It's what they _could_ resolve, if they allowed for
extension methods on type names as well as instances. But they don't, so
they don't.
[...]
And it would have to be called with:

PrintName(typeof(string));

Is there any way of moving the typeof inside the function, so you can
just call:

PrintName(string);
As you suspected, no. The type name itself is only useful for declaring
other things. It doesn't resolve to an object itself. That's what
"typeof()" is for.

Pete
Jun 27 '08 #15

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

Similar topics

13
by: Axehelm | last post by:
Okay, I'm in a debate over whether or not static methods are a good idea in a general domain class. I'm personally not a fan of static methods but we seem to be using them to load an object. ...
4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
3
by: Steven D'Aprano | last post by:
I've been doing a lot of reading about static methods in Python, and I'm not exactly sure what they are useful for or why they were introduced. Here is a typical description of them, this one...
1
by: baylor | last post by:
In C#, an interface cannot mark any method as static. i'm told the ILASM supports it but i've never tested that Two questions. First, why? OK, i've heard the reason about interfaces being...
11
by: Saumya | last post by:
Hi, I didn't know how else to express myself in the subject line, but what I want to know is this: <b>I have a class A, so what do I have to do to ensure that no one can derive from it?</b> ...
3
by: Mauzi | last post by:
hi, this may sound odd and noob like, but what is the 'big' difference between static and non-static funcitons ? is there any performace differnce? what is the best way to use them ? thnx ...
3
by: Jay | last post by:
Why are there static methods in C#. In C++ static was applied to data only (I believe) and it meant that the static piece of data was not a part of the object but only a part of the class (one...
12
by: chandu | last post by:
hello, i want to know usage of static methods in a class. is it advantageous or disadvantage to use more static methods in a class. thank u
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.