473,657 Members | 2,378 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I get the class name in a static method or property


If I have an object I know I can get the name of the class but can I get the class name in the following scenario :

public class ParentClass
{
public static string ClassName
{
get
{
return "ParentClas s"
}

}
}
public class ChildClass : ParentClass
{

}
So that ChildClass.Clas sName returns "ChildClass " and ParentClass.Cla ssName returns "ParentClas s"

It may seem a bit strange but I really want to use it to return a token based on the class name that can be used for reading data
from an xml file and that contains a list of these classes.

I would like to be able to base the read on just knowing the class name and not have to store static data in each class which could
be calculated from the class name.

So, I will be able to write

MyStoredData.Ge tData(ChildClas s.ClassName) and it will return all the records in the xml of type ChildClass and MyStoredData
encapsulates the reading of data and GetData is a static method
It is not important whether I get the class name from a method or a property.

Any ideas welcome. Hope it makes sense.

Steve
Sep 2 '08 #1
10 1765
The cleanest answer I can suggest is generics - have GetData<T>(), so
you call GetData<ChildCl ass>(), then inside GetData<T>() you can use
typeof(T).Name, or access attribute metadata from typeof(T) such as
XmlTypeAttribut e.

Marc
Sep 2 '08 #2
steve <s_******@yahoo .comwrote:
>
If I have an object I know I can get the name of the class
but can I get the class name in the following scenario :

public class ParentClass
{
public static string ClassName
{
get
{
return "ParentClas s"
}

}
}
public class ChildClass : ParentClass
{

}
So that ChildClass.Clas sName returns "ChildClass "
and ParentClass.Cla ssName returns "ParentClas s"
No, you can't do this. In fact, if you look at the generated code for
"ChildClass.Cla ssName" you'll see it's *actually* a call to
"ParentClass.Cl assName".
It may seem a bit strange but I really want to use it to return a
token based on the class name that can be used for reading data from
an xml file and that contains a list of these classes.

I would like to be able to base the read on just knowing the class
name and not have to store static data in each class which could be
calculated from the class name.

So, I will be able to write

MyStoredData.Ge tData(ChildClas s.ClassName) and it will return all the
records in the xml of type ChildClass and MyStoredData encapsulates
the reading of data and GetData is a static method

It is not important whether I get the class name from a method or a
property.

Any ideas welcome. Hope it makes sense.
Could you change to use generics instead?

MyStoredData.Ge tData<ChildClas s>(...)

?

--
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
Sep 2 '08 #3
On Tue, 02 Sep 2008 13:33:25 -0700, steve <s_******@yahoo .comwrote:
[...]
So that ChildClass.Clas sName returns "ChildClass " and
ParentClass.Cla ssName returns "ParentClas s"
Since you cannot call the static member (method or property) without
knowing the class name already, how would this benefit you? How is
writing this:

MyStoredData.Ge tData(ChildClas s.ClassName);

better than this:

MyStoredData.Ge tData("ChildCla ss");

or even:

MyStoredData.Ge tData(typeof(Ch ildClass).GetNa me());

?

More generally, while it's not your question specifically, .NET already
has serialization support built in, including being able to serialize to
an XML file. It sounds a little like you might be reinventing the wheel
here.

Pete
Sep 2 '08 #4

It helps me because I do not use the class name. I manipulate it to give me an xml token which is based on the class name and I
would have to include this logic in all the methods that need to create the token.

I wrote xml read routine a long time ago. I didn't know about the serialization stuff at that time - or if it existed. But, anyway
the class has a lot of variables which are not always used but I have logic in my read/write routines to allow me to ignore writing
data based on the values in certain fields. I am not sure I could have done this with the serialization that is in the Xml
namespace. It saves me an awful lot of space in the output xml file.

I realized that I did have a ChildClass object around when I was making the call so I made them non-static. I guess I could have
created a static conversion routine and hidden that in the parent class.

I will take a look at the generics stuff.

Thanks to all,
Steve

On Tue, 02 Sep 2008 14:00:05 -0700, "Peter Duniho" <Np*********@nn owslpianmk.comw rote:
>On Tue, 02 Sep 2008 13:33:25 -0700, steve <s_******@yahoo .comwrote:
>[...]
So that ChildClass.Clas sName returns "ChildClass " and
ParentClass.Cl assName returns "ParentClas s"

Since you cannot call the static member (method or property) without
knowing the class name already, how would this benefit you? How is
writing this:

MyStoredData.Ge tData(ChildClas s.ClassName);

better than this:

MyStoredData.Ge tData("ChildCla ss");

or even:

MyStoredData.Ge tData(typeof(Ch ildClass).GetNa me());

?

More generally, while it's not your question specifically, .NET already
has serialization support built in, including being able to serialize to
an XML file. It sounds a little like you might be reinventing the wheel
here.

Pete
Sep 2 '08 #5
On Tue, 02 Sep 2008 15:43:16 -0700, steve <s_******@yahoo .comwrote:
It helps me because I do not use the class name. I manipulate it to give
me an xml token which is based on the class name and I
would have to include this logic in all the methods that need to create
the token.
Or, you could just create a single static method somewhere that does that
transformation for you, based on an explicitly-given class name. That
logic doesn't have to be in the class, and it might even be more
appropriate for it _not_ to be there (depending on how you've encapsulated
the serialization logic).

If not in the type you're serializing, it could even be an extension
method, either on the Type or String class (depending on what syntax you
prefer).
I wrote xml read routine a long time ago. I didn't know about the
serialization stuff at that time - or if it existed. But, anyway
the class has a lot of variables which are not always used but I have
logic in my read/write routines to allow me to ignore writing
data based on the values in certain fields. I am not sure I could have
done this with the serialization that is in the Xml
namespace. It saves me an awful lot of space in the output xml file.
I get the various serialization types mixed up, so I can't tell you which
one specifically I've used more (such as it is...I don't write a lot of
serialization code). But I can tell you that the one I've used more
allows all sorts of customization and control over the serialization.

Pete
Sep 2 '08 #6
I am not sure I could have done this with the serialization that is in the Xml
namespace. It saves me an awful lot of space in the output xml file.
Sure you can... for the simple cases you can just specify
[DefaultValue(.. .)]; for more complex cases you just add a bool
ShouldSerialize {prop-name}() method. This method pattern is inherited
from System.Componen tModel, where it works even if private, but IIRC
XmlSerializer likes the method to be public (you can always hide it
from intellisense with EditorBrowsable Attribute). Finally, for the
most extreme cases you can implement IXmlSerializabl e (although this
largely defeats the point).

If you are talking about whitespace etc, then XmlWriterSettin gs is
what you want.

Marc
Sep 3 '08 #7

I have been looking at the book "Beginning XML with C# 2008" by Joshi and I can't see anything that would allow me to do what I want
or what you suggest.

A typical example would be writing out a Polygon class where I can give a different color to each edge of the polygon. But, in the
majority of cases all the edges will be the same color or not drawn so that if I write out a node or attribute indicating the edges
do not need to be drawn I know I don't need to write out the attributes for each of the sides.

Also multiple classes get written to the same xml file. Would that be a problem for the serializer?

If you know of a good source to read about this it would be appreciated.

Thanks,
Steve


On Tue, 2 Sep 2008 23:16:11 -0700 (PDT), Marc Gravell <ma**********@g mail.comwrote:
>I am not sure I could have done this with the serialization that is in the Xml
namespace. It saves me an awful lot of space in the output xml file.

Sure you can... for the simple cases you can just specify
[DefaultValue(.. .)]; for more complex cases you just add a bool
ShouldSerializ e{prop-name}() method. This method pattern is inherited
from System.Componen tModel, where it works even if private, but IIRC
XmlSerialize r likes the method to be public (you can always hide it
from intellisense with EditorBrowsable Attribute). Finally, for the
most extreme cases you can implement IXmlSerializabl e (although this
largely defeats the point).

If you are talking about whitespace etc, then XmlWriterSettin gs is
what you want.

Marc
Sep 3 '08 #8
Also multiple classes get written to the same xml file. Would that be a problem for the serializer?

As long as they are expected, for example via XmlIncludeAttri bute for
sub-types
If you know of a good source to read about this it would be appreciated.
msdn:
http://msdn.microsoft.com/en-us/library/83y7df3e.aspx
http://msdn.microsoft.com/en-us/library/2baksw0z.aspx
http://msdn.microsoft.com/en-us/library/athddy89.aspx

I can't find a good source for ShouldSerialize , but it works: in the
following, Foo is written, Bar isn't:

using System;
using System.Componen tModel;
using System.Xml.Seri alization;

[Serializable, XmlType("test")]
public class Test
{
[XmlAttribute("f oo")]
public string Foo { get; set; }
[EditorBrowsable (EditorBrowsabl eState.Never)]
public bool ShouldSerialize Foo() { return true; }
[XmlAttribute("b ar")]
public string Bar { get; set; }
[EditorBrowsable (EditorBrowsabl eState.Never)]
public bool ShouldSerialize Bar() { return false; }
}

static class Program
{
static void Main()
{
XmlSerializer xser = new XmlSerializer(t ypeof(Test));
Test obj = new Test { Foo = "abc", Bar = "def" };
xser.Serialize( Console.Out, obj);
}
}
Sep 3 '08 #9
(obviously the ShouldSerialize methods would normally check some other
state to make the decision - for a more interesting example, consider
a rectangle that serializes @width and @height if non-square, and
@size otherwise):

using System;
using System.Componen tModel;
using System.Xml.Seri alization;

[Serializable, XmlType("rectan gle")]
public class Rectangle
{
[XmlAttribute("w idth")]
public int Width { get; set; }
[EditorBrowsable (EditorBrowsabl eState.Never)]
public bool ShouldSerialize Width() { return Width != Height; }

[XmlAttribute("h eight")]
public int Height { get; set; }
[EditorBrowsable (EditorBrowsabl eState.Never)]
public bool ShouldSerialize Height() { return Width != Height; }

[XmlAttribute("s ize")]
public int Size {
get {
if (Width == Height) return Width;
throw new InvalidOperatio nException("Siz e only valid for
squares");
}
set {Width = Height = value;}
}

[EditorBrowsable (EditorBrowsabl eState.Never)]
public bool ShouldSerialize Size() { return Width == Height; }
}

static class Program
{
static void Main()
{
XmlSerializer xser = new XmlSerializer(t ypeof(Rectangle ));
Rectangle rect = new Rectangle { Width = 2, Height = 3 };
xser.Serialize( Console.Out, rect);
rect.Width = 3; // should now be square
xser.Serialize( Console.Out, rect);
}
}
Sep 3 '08 #10

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

Similar topics

1
2431
by: Phil Powell | last post by:
Consider this: class ActionHandler { /*------------------------------------------------------------------------------------------------------------------------------------------------------------------- This class will be a singleton class structure by calling its constructor by reference only (prefixed by '&'). Is primarly used to reference its errorArray Array property as a single reference to allow for static usage
1
1570
by: Phil Powell | last post by:
Consider these two classes. Class Accepter in placement_classes.inc.php works as a form validation object, and it works like a charm: PHP: // placement_classes.inc.php - THIS ONE WORKS! class Accepter { function Accepter() {
10
3478
by: Not Available | last post by:
On the host server: namespace JCart.Common public class JCartConfiguration : IConfigurationSectionHandler private static String dbConnectionString; public static String ConnectionString { get { return dbConnectionString;
2
2057
by: Stan | last post by:
I need to change the Url property in a web service proxy class in a generic way. The proxy class looks like this public class Sender : System.Web.Services.Protocols.SoapHttpClientProtocol ... If I instantiate the proxy class, I can set its Url property localhost.Sender oSender = new localhost.Sender(); // proxy clas oSender.Url = "http://server/webservice/s.asmx"
0
1607
by: Ed West | last post by:
Hello, I am wondering about best practices for class hierarchies and using ADO.Net, especially the DataSet update/delete commands and the data relations... this needs to package/unpackage to xml for client/server sending. The class properties pretty much correspond to database tables. This is a pretty long question so thanks in advance for reading and commenting!
6
1762
by: Davinci_Jeremie | last post by:
Hi Newbee here to C# I have a simple questions... In a Hello world example how does the class object Hello exist with out creating it? I come from object pascal where everything object is created then used. In object pascal you can call a method a "class" and it means you can call it by the name of the class and the function name with out creating it like "Hello.Main()" is that true for key word "static"? Also what if I have more...
13
1744
by: Liz | last post by:
ok, this is really simple stuff, or it should be ... but I'm stuck In a Windows Forms app, I have something resembling this: Form1.cs ======== namespace NS Class Form1
14
33260
by: Dave Booker | last post by:
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;} } }
49
5785
by: Ben Voigt [C++ MVP] | last post by:
I'm trying to construct a compelling example of the need for a language feature, with full support for generics, to introduce all static members and nested classes of another type into the current name search scope. i.e. a very simple application would be class ManyComputations { calling System.Math;
0
8312
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
8827
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
8732
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
8504
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
5632
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
4318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2732
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
1959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1622
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.