473,692 Members | 2,089 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 1768
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
2435
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
1571
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
3481
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
2058
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
1765
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
1745
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
33270
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
5793
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
8600
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
8535
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
9079
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
8796
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
7626
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
6457
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
4322
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4553
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2968
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

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.