473,547 Members | 2,553 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get type and value of a MemberInfo m that in fact is a true bool?

Hi all,

I have a question I am unable solve.

I have an inheritance graph like this:
// CAR ----- MUSICAR ---- NICECAR
// \ \
// \ +------ OLDCAR
// \
// +---- HOMEMADECAR

All originate from Car. In musiCar I introduce "public bool hasStereo"
that I can assess with a cast and the test
bool mightHaveStereo = myCar.GetType() .IsSubclassOf(t ypeof(musiCar)) ;
(is this the best way test that BTW?)

Now I "want" another class that does not derive from musiCar but that
has an identical member hasStereo. I reach it and I can print it on
the console. I see that it is a bool and that it has the "correct"
name by using the following snippet:

Type T = myCar.GetType() ;
MemberInfo[] MIF = T.GetMembers();

foreach (MemberInfo m in MIF)
{
if (m.Name == "hasStereo" && T != typeof(niceCar) )
{
Console.WriteLi ne(" - '{0}' : '{1}' ", m.Name, m);
}
}
}

Is there any way to get the value of myCar? I was hoping on something
like this:
((T) myCar).m;
or
if (m.isBool) myBool = ((bool)m);

See below for the complete example.

Thanks,
Per

Home: http://www.pererikstrandberg.se/blog/ .
Optimization in .NET: http://tomopt.com/tomnet/ .

-------------------------
using System;
using System.Reflecti on;

class Program
{
//
// Inheritance diagram
//
// CAR ----- MUSICAR ---- NICECAR
// \ \
// \ +------ OLDCAR
// \
// +---- HOMEMADECAR
// base class
public abstract class Car
{
public string nickname;
public string color;
public int miles;
}

// class for a car that might have a stereo
public abstract class musiCar : Car
{
public bool hasStereo;
}

// inherited class
public class niceCar : musiCar
{
public bool hasMP314Player;
}

// inherited class
public class oldCar : musiCar
{
public int age;
}

// car that is only related to the base class car
public class homeMadeCar : Car
{
public bool hasStereo;
public bool isEpa;
}

public static void displayCar(Car myCar)
{
Console.WriteLi ne("The {0} car...", myCar.color);
Console.WriteLi ne(" - is called '{0}'", myCar.nickname) ;
Console.WriteLi ne(" - has run for '{0}' miles", myCar.miles);

// is it a musicar?
if (myCar.GetType( ).IsSubclassOf( typeof(musiCar) ))
{
if (((musiCar)myCa r).hasStereo)
Console.WriteLi ne(" - has a stero");
else
Console.WriteLi ne(" - has no stero");

// is it an old car?
if (myCar.GetType( ) == typeof(oldCar))
{
Console.WriteLi ne(" - is {0} years old",
((oldCar)myCar) .age);
}

// is it a nice car?
if (myCar.GetType( ) == typeof(niceCar) )
{
if (((niceCar)myCa r).hasMP314Play er)
Console.WriteLi ne(" - has an MP314 player");
else
Console.WriteLi ne(" - has no MP314 player");
}
}

// what if it is some other class that also might have a stereo
Type T = myCar.GetType() ;
MemberInfo[] MIF = T.GetMembers();

foreach (MemberInfo m in MIF)
{
if (m.Name == "hasStereo" && T != typeof(niceCar) )
{
Console.WriteLi ne(" - '{0}' : '{1}' ", m.Name, m);
}
}
}

static void Main(string[] args)
{

oldCar c1 = new oldCar();
c1.age = 25;
c1.color = "beige";
c1.hasStereo = false;
c1.miles = int.MaxValue / 2;
c1.nickname = "ugly betty";

niceCar c2 = new niceCar();
c2.color = "light blue metallic";
c2.hasMP314Play er = true;
c2.hasStereo = c2.hasMP314Play er;
c2.miles = 1337;
c2.nickname = "Turing the Tempest";

homeMadeCar c3 = new homeMadeCar();
c3.color = "black";
c3.hasStereo = true;
c3.isEpa = true;
c3.miles = 555;
c3.nickname = "KB::P_WAGO N";

Console.WriteLi ne("CAR 1");
displayCar(c1);

Console.WriteLi ne("CAR 2");
displayCar(c2);

Console.WriteLi ne("\"CAR\" 3");
displayCar(c3);

}
}

Mar 12 '07 #1
5 3965
BTW; the out put is:

C:\temp>dynamic _cast.exe
CAR 1
The beige car...
- is called 'ugly betty'
- has run for '1073741823' miles
- has no stero
- is 25 years old
- 'hasStereo' : 'Boolean hasStereo'
CAR 2
The light blue metallic car...
- is called 'Turing the Tempest'
- has run for '1337' miles
- has a stero
- has an MP314 player
"CAR" 3
The black car...
- is called 'KB::P_WAGON'
- has run for '555' miles
- 'hasStereo' : 'Boolean hasStereo'

-----------------

Per

Home: http://www.pererikstrandberg.se/blog/ .
Optimization in .NET: http://tomopt.com/tomnet/ .

Mar 12 '07 #2
per9000 <pe*****@gmail. comwrote:
Hi all,

I have a question I am unable solve.

I have an inheritance graph like this:
// CAR ----- MUSICAR ---- NICECAR
// \ \
// \ +------ OLDCAR
// \
// +---- HOMEMADECAR

All originate from Car. In musiCar I introduce "public bool hasStereo"
that I can assess with a cast and the test
bool mightHaveStereo = myCar.GetType() .IsSubclassOf(t ypeof(musiCar)) ;
(is this the best way test that BTW?)
No, you just need:

bool mightHaveStereo = (myCar is musiCar);
Now I "want" another class that does not derive from musiCar but that
has an identical member hasStereo. I reach it and I can print it on
the console.
It would be better to have an interface which both classes implemented,
so you didn't need to use reflection...
I see that it is a bool and that it has the "correct"
name by using the following snippet:

Type T = myCar.GetType() ;
MemberInfo[] MIF = T.GetMembers();

foreach (MemberInfo m in MIF)
{
if (m.Name == "hasStereo" && T != typeof(niceCar) )
{
Console.WriteLi ne(" - '{0}' : '{1}' ", m.Name, m);
}
}
}
Why don't you just use Type.GetMethod( ) or Type.GetPropert y()?
Is there any way to get the value of myCar? I was hoping on something
like this:
((T) myCar).m;
or
if (m.isBool) myBool = ((bool)m);
It depends what kind of member it is - if it's a method, use
MethodInfo.Invo ke. If it's a property, use PropertyInfo.Ge tValue.

As I say, it would be better not to use reflection in the first
place...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 12 '07 #3
Thanks Jon,

you pushed me in the right direction.

The testing for a stereo now looks like this:

// what if it is some other class that also might have a stereo
if (!(myCar is musiCar))
{
try
{
Type T = myCar.GetType() ;
FieldInfo field = T.GetField("has Stereo");

if ((bool)field.Ge tValue(myCar))
Console.WriteLi ne(" - has a stereo :)");
else
Console.WriteLi ne(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLi ne(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLi ne(" {0}", ex.Message);
}
}

-----------------

Per

A little more about this forum entry:
http://www.pererikstrandberg.se/blog...tanceAndFields
Home: http://www.pererikstrandberg.se/blog/ .
Optimization in .NET: http://tomopt.com/tomnet/ .

On 12 Mar, 19:08, Jon Skeet [C# MVP] <s...@pobox.com wrote:
per9000 <per9...@gmail. comwrote:
Hi all,
I have a question I am unable solve.
I have an inheritance graph like this:
// CAR ----- MUSICAR ---- NICECAR
// \ \
// \ +------ OLDCAR
// \
// +---- HOMEMADECAR
All originate from Car. In musiCar I introduce "public bool hasStereo"
that I can assess with a cast and the test
bool mightHaveStereo = myCar.GetType() .IsSubclassOf(t ypeof(musiCar)) ;
(is this the best way test that BTW?)

No, you just need:

bool mightHaveStereo = (myCar is musiCar);
Now I "want" another class that does not derive from musiCar but that
has an identical member hasStereo. I reach it and I can print it on
the console.

It would be better to have an interface which both classes implemented,
so you didn't need to use reflection...
I see that it is a bool and that it has the "correct"
name by using the following snippet:
Type T = myCar.GetType() ;
MemberInfo[] MIF = T.GetMembers();
foreach (MemberInfo m in MIF)
{
if (m.Name == "hasStereo" && T != typeof(niceCar) )
{
Console.WriteLi ne(" - '{0}' : '{1}' ", m.Name, m);
}
}
}

Why don't you just use Type.GetMethod( ) or Type.GetPropert y()?
Is there any way to get the value of myCar? I was hoping on something
like this:
((T) myCar).m;
or
if (m.isBool) myBool = ((bool)m);

It depends what kind of member it is - if it's a method, use
MethodInfo.Invo ke. If it's a property, use PropertyInfo.Ge tValue.

As I say, it would be better not to use reflection in the first
place...

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 13 '07 #4
per9000 <pe*****@gmail. comwrote:
you pushed me in the right direction.

The testing for a stereo now looks like this:

// what if it is some other class that also might have a stereo
if (!(myCar is musiCar))
{
try
{
Type T = myCar.GetType() ;
FieldInfo field = T.GetField("has Stereo");

if ((bool)field.Ge tValue(myCar))
Console.WriteLi ne(" - has a stereo :)");
else
Console.WriteLi ne(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLi ne(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLi ne(" {0}", ex.Message);
}
}
That means you're relying on a public hasStereo field. You shouldn't
have a public field to start with, IMO. An interface would be *so* much
nicer. Your test would be (horrible naming aside):

IPossiblyMusica lVehicle car = myCar as IPossiblyMusica lVehicle;
if (car != null)
{
if (car.HasStereo)
{
Console.WriteLi ne ("The car has a stereo");
}
else
{
Console.WriteLi ne ("The car doesn't have a stereo");
}
}

(Note also that you're using exceptions to catch things you could
easily test for - and reporting one particular error which could well
not be the cause of the exception.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 13 '07 #5
*wearing silly hat, standing in a corner, chanting "I will always
think before I implement my inheritance graph"*

Indeed, I would never do such tests in a real world scenario, I love
OO-programming and my above example is an example of failed oo-
programming. But still: it is nice to know "how you can do it", not
just knowing "how you should do it".

BTW: IPossiblyMusica lVehicle isn't that bad - I like
LongAndStrangeC lassNamingUsage . (Short names quickly become hard to
understand, f.x: II = Interface(To)Ip od or if you integrate an Ipod
with an Iguana: IIII (Interface(To)I podIntegratedIg uana))

class BobsIguana : IIII
{
// ...
}

/P
--

Per Erik Strandberg

Home: http://www.pererikstrandberg.se/blog/ .
Optimization in .NET: http://tomopt.com/tomnet/ .

On Mar 13, 8:42 pm, Jon Skeet [C# MVP] <s...@pobox.com wrote:
per9000 <per9...@gmail. comwrote:
you pushed me in the right direction.
The testing for a stereo now looks like this:
// what if it is some other class that also might have a stereo
if (!(myCar is musiCar))
{
try
{
Type T = myCar.GetType() ;
FieldInfo field = T.GetField("has Stereo");
if ((bool)field.Ge tValue(myCar))
Console.WriteLi ne(" - has a stereo :)");
else
Console.WriteLi ne(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLi ne(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLi ne(" {0}", ex.Message);
}
}

That means you're relying on a public hasStereo field. You shouldn't
have a public field to start with, IMO. An interface would be *so* much
nicer. Your test would be (horrible naming aside):

IPossiblyMusica lVehicle car = myCar as IPossiblyMusica lVehicle;
if (car != null)
{
if (car.HasStereo)
{
Console.WriteLi ne ("The car has a stereo");
}
else
{
Console.WriteLi ne ("The car doesn't have a stereo");
}

}

(Note also that you're using exceptions to catch things you could
easily test for - and reporting one particular error which could well
not be the cause of the exception.)

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 14 '07 #6

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

Similar topics

5
2911
by: jorfei | last post by:
I have written a component with a property IPAdrress of type System.Net.IPAddress. To ease the configuration of the component at design time, I have written a type converter for the type System.Net.IPAddress. The type System.Net.IPAddress, as you know, is provided by Microsoft and I have no choice but to apply the type converter on the...
4
1798
by: Scott Graham | last post by:
Hi, In the following code, is there any way to get rid of the method marked below (that has signature static void Func(Base o))? It seems that the language should be able to dispatch to the correct function for me based on the actual type of the object, but I can't figure out how to write that. (I'm aware that making Func a virtual...
1
1223
by: Dave Parry | last post by:
Hi, I would like to hear peoples thoughts on passing a value type by reference and then trying to store this ref in a member so it can be updated elsewhere, whereby I want the referenced value to be updated. eg. class A {
1
1971
by: Vijai Kalyan | last post by:
Oops, maybe that is the standard. I don't have a copy unfortunately, but here goes. I was experimenting and wrote the following code: #include <limits.h> #include <stdexcept> #include <sstream> namespace exceptions { class out_of_range : public std::exception
4
2368
by: Mathieu Cartoixa | last post by:
Hi, I have been annoyed in one of my recent projects with a problem related to the explicit implementation of an interface on a value type. I will take an example to show the problem. Say we have this simple interface : interface IInitializable { void Init();
76
4834
by: KimmoA | last post by:
First of all: I love C and think that it's beautiful. However, there is at least one MAJOR flaw: the lack of a boolean type. OK. Some of you might refer to C99 and its _Bool (what's up with the uppercase 'B' anyway?) and the header you can include (apparently) to get a real "bool". This isn't my point, however -- it should have been there...
2
29978
by: Andrus | last post by:
I'm trying to compile myGeneration PropertyCollectionAll.cs file with VCS Express 2005 bot got error Error 1 The type or namespace name 'Collection' could not be found (are you missing a using directive or an assembly reference?) PropertyCollectionAll.cs 17 39 I looked to .NET 2 help and found that Collection class is included in...
13
7011
by: a2z | last post by:
Hi all, Can someone throw some light on the implemetation of bool data type in C++? I have heard that it is bit based, but want to confirm this information. Is there any source code where I can look into? ~Thanks, Ramesh.
14
9479
by: Martin Wells | last post by:
I come from C++, and there's a type called "bool" in C++. It works exactly like any other integer type except that when promoted, it either becomes a one or a zero, so you can you bitwise operators as if they were logical operators: bool a = 5, b = 6; if (a == b) DoSomething; /* This will execute */ What type is commonly used in C for...
0
7510
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...
0
7437
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...
0
7947
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...
0
6032
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...
0
5081
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...
0
3493
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...
0
3473
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1923
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
0
748
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...

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.