473,748 Members | 2,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(baseClas s).FullName;
}
}

what I want is for:

class someClass : baseClass
{
....
}

and to be able to call someClass.Class Name() 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 1635
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(baseClas s).FullName;
}
}

what I want is for:

class someClass : baseClass
{
...
}

and to be able to call someClass.Class Name() 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.Class Name()

better than:

typeof(someClas s).FullName

?

Arne
Jun 27 '08 #2
d-42 <db********@gma il.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(baseClas s).FullName;
}
}

what I want is for:

class someClass : baseClass
{
...
}

and to be able to call someClass.Class Name() 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.Class Name(), the compiler will replace it with
baseClass.Class Name() in the generated IL.

--
Jon Skeet - <sk***@pobox.co m>
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.d kwrote:
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(baseClas s).FullName;
}
}
what I want is for:
class someClass : baseClass
{
...
}
and to be able to call someClass.Class Name() 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.Class Name()

better than:

typeof(someClas s).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.co mwrote:
d-42 <db.pors...@gma il.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.FullN ame() 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.Class Name(), the compiler will replace it with
baseClass.Class Name() 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).FullN ame;}

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

public string someClass.Class Name() { return
typeof(someClas s).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********@gma il.comwrote:
>Why is:

someClass.Clas sName()

better than:

typeof(someCla ss).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.Clas sName()" (or IMHO it'd be a property and you'd write
"someClass.Clas sName", but whatever).

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

Pete
Jun 27 '08 #6
On May 26, 4:37 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Mon, 26 May 2008 16:15:41 -0700, d-42 <db.pors...@gma il.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(someClas s).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(someClas s).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.Clas sName()" (or IMHO it'd be a property and you'd write
"someClass.Clas sName", but whatever).
Agreed. I'd prefer a property to a method.
How is this significantly better than simply writing
"typeof(someCla ss).FullName"?
That's basically the same as asking:

How is writing myInt.ToString( ) significantly better than
Convert.ToStrin g(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.ToStrin g(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...@gma il.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.FullN ame() 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.FullN ame(), only
baseClass.FullN ame() - 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********@gma il.comwrote:
[...]
>How is this significantly better than simply writing
"typeof(someCl ass).FullName"?

That's basically the same as asking:

How is writing myInt.ToString( ) significantly better than
Convert.ToStrin g(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.ToStrin g(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.ToStrin g() 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(someCla ss).FullName" might not look quite as nice as
"someClass.Full Name". 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.co mwrote:
On May 27, 12:35 am, d-42 <db.pors...@gma il.comwrote:
The usage is that: someClass.FullN ame() 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.FullN ame(), only
baseClass.FullN ame() - 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

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

Similar topics

13
10731
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. For example if you have an Employee class rather then instantiating an instance you call a static method 'GetEmployees' and it returns a List of Employee objects. I'm looking for what other people are doing and if you feel this is a good or bad...
4
8031
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 in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
3
1996
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 from Guido: "The new descriptor API makes it possible to add static methods and class methods. Static methods are easy to describe: they behave pretty much like static methods in C++ or Java." http://www.python.org/2.2.3/descrintro.html
1
2209
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 allocated on the stack but that's not a real reason. Which is OK because this isn't a real question, it's just a complaint dressed up to look like a reason Second question. If a language doesn't support a fairly obvious feature, one has to wonder if...
11
1617
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> Saumya
3
9758
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 mauzi
3
2088
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 copy of data as opposed to multiple instances of the class) C# is now applying the static concept to methods. Why?, I thought that only one copy of the methods were loaded into memory not matter how many instances were created. Is this different...
12
3581
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
5849
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 the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
0
8995
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9561
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9381
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
9332
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
8252
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...
1
6799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
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();...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2217
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.