473,480 Members | 2268 Online
Bytes | Software Development & Data Engineering Community
Create 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(typeof(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.WriteLine(" - '{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.Reflection;

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.WriteLine("The {0} car...", myCar.color);
Console.WriteLine(" - is called '{0}'", myCar.nickname);
Console.WriteLine(" - has run for '{0}' miles", myCar.miles);

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

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

// is it a nice car?
if (myCar.GetType() == typeof(niceCar))
{
if (((niceCar)myCar).hasMP314Player)
Console.WriteLine(" - has an MP314 player");
else
Console.WriteLine(" - 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.WriteLine(" - '{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.hasMP314Player = true;
c2.hasStereo = c2.hasMP314Player;
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_WAGON";

Console.WriteLine("CAR 1");
displayCar(c1);

Console.WriteLine("CAR 2");
displayCar(c2);

Console.WriteLine("\"CAR\" 3");
displayCar(c3);

}
}

Mar 12 '07 #1
5 3955
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(typeof(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.WriteLine(" - '{0}' : '{1}' ", m.Name, m);
}
}
}
Why don't you just use Type.GetMethod() or Type.GetProperty()?
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.Invoke. If it's a property, use PropertyInfo.GetValue.

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

--
Jon Skeet - <sk***@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 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("hasStereo");

if ((bool)field.GetValue(myCar))
Console.WriteLine(" - has a stereo :)");
else
Console.WriteLine(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLine(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLine(" {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.comwrote:
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(typeof(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.WriteLine(" - '{0}' : '{1}' ", m.Name, m);
}
}
}

Why don't you just use Type.GetMethod() or Type.GetProperty()?
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.Invoke. If it's a property, use PropertyInfo.GetValue.

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("hasStereo");

if ((bool)field.GetValue(myCar))
Console.WriteLine(" - has a stereo :)");
else
Console.WriteLine(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLine(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLine(" {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):

IPossiblyMusicalVehicle car = myCar as IPossiblyMusicalVehicle;
if (car != null)
{
if (car.HasStereo)
{
Console.WriteLine ("The car has a stereo");
}
else
{
Console.WriteLine ("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.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 #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: IPossiblyMusicalVehicle isn't that bad - I like
LongAndStrangeClassNamingUsage. (Short names quickly become hard to
understand, f.x: II = Interface(To)Ipod or if you integrate an Ipod
with an Iguana: IIII (Interface(To)IpodIntegratedIguana))

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.comwrote:
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("hasStereo");
if ((bool)field.GetValue(myCar))
Console.WriteLine(" - has a stereo :)");
else
Console.WriteLine(" - has no stereo :)");
}
catch (Exception ex)
{
Console.WriteLine(" the 'hasStereo' of this car was not a
bool...");
Console.WriteLine(" {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):

IPossiblyMusicalVehicle car = myCar as IPossiblyMusicalVehicle;
if (car != null)
{
if (car.HasStereo)
{
Console.WriteLine ("The car has a stereo");
}
else
{
Console.WriteLine ("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
2899
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...
4
1793
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...
1
1211
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...
1
1966
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>...
4
2360
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...
76
4802
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...
2
29963
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...
13
7004
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...
14
9475
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...
0
7054
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,...
0
7057
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,...
0
7102
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...
1
6756
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...
0
5357
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,...
1
4798
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...
0
4495
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...
0
3008
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...
1
570
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.