473,785 Members | 2,432 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GetType and variables declared as an interface type

Bob
This has been bugging me for a while now.

GetType isn't availble for variables decalred as interface types, I have to
DirectCast(some variable, Object).

In example:

Sub SomeSub(ByVal Dictionary as IDictionary)
If Dictionary is Nothing Then Return
Dim o as Object = DirectCast(Dict ionary, Object)
If GetType(ISomeIn terface).IsAssi gnableFrom(o.Ge tType) Then
'<... some code...>
End If
End Sub

Does this mean that it is possible to have variable types that are not derived
from Object? And if not, why aren't all variables treated as Objects?

Bob

Nov 20 '05 #1
10 11800
"Bob" <no*****@nospam .net> schrieb
This has been bugging me for a while now.

GetType isn't availble for variables decalred as interface types, I
have to DirectCast(some variable, Object).

In example:

Sub SomeSub(ByVal Dictionary as IDictionary)
If Dictionary is Nothing Then Return
Dim o as Object = DirectCast(Dict ionary, Object)
You don't need Directcast here:
dim o as object = dictionary
If GetType(ISomeIn terface).IsAssi gnableFrom(o.Ge tType) Then
'<... some code...>
End If
End Sub

Does this mean that it is possible to have variable types that are
not derived from Object?
No.
And if not, why aren't all variables treated
as Objects?


The Interface does not have a GetType method.
--
Armin

Nov 20 '05 #2
"Bob" <no*****@nospam .net> schrieb:
GetType isn't availble for variables decalred as interface
types, I have to DirectCast(some variable, Object).
'DirectCast' to 'Object' doesn't make sense, because 'Object' is the more
general type.
Does this mean that it is possible to have variable types that
are not derived from Object?
No.
And if not, why aren't all variables treated as Objects?


An interface cannot be instantiated, there cannot be objects with the type
of an interface. Classes can implement interfaces and classes can get
instantiated.

--
Herfried K. Wagner
MVP · VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #3
Hi Bob,

Pardon me if this is irrelevant Bob, I'm not sure I understand the question properly so a bit of a ramble about Interfaces...

|| Sub SomeSub(ByVal Dictionary as IDictionary)

You can't just call this with any old variable - it has to be one whose class implements the given interface. In this case, for
example, a HashTable.

One of the purposes of using an interface for a method parameter is to restrict what can be done with the variable. For example,
the HashTable provides Clone, ContainsKey and ContainsValue, amongst others. These are not available to the Dictionary parameter as
they are HashTable specific.

It's perhaps clearer if you have two disparate objects, say an Elephant and a BananaBalloon (as at the seaside). Both of these
might implement an IPeopleCarrier interface with such properties as Capacity, etc.

There's no way that you could define a method which takes either an Elephant or a BananaBalloon but no other object - except by
using the interface, eg Sub LoadUp (oCarrier As IPeopleCarrier) .

=============== =============== ===
Having written this, and played around in VB, I wasn't happy that I was answering you, so I decided to try the same in C#.

|| GetType isn't availble for variables decalred as interface types

True, I'm afraid. Have a look at the following C# code:

static void Main()
{ HmmmInterfaces (new Hashtable()); }

static void HmmmInterfaces (IDictionary d)
{
Hashtable h = new Hashtable();
Type th = h.GetType();
Type td = d.GetType(); // Won't compile in VB. It says that
// GetType is not a member of IDictionary.
}

This is perfectly acceptable C# and, with this code, td is HashTable.
In VB you can't get call GetType on d.

So now I think I understand your question. - How are you supposed to know what you are dealing with?

Well, you're right about the DirectCast.

This will give HashTable
Dim td As Type = DirectCast(d, Object).GetType
If td Is GetType(Hashtab le) Then

And TypeOf is available too.

This will be True only for HashTable
If TypeOf d Is Hashtable Then

This will be always be True (as the parameter is an IDictionary)
If TypeOf d Is IDictionary Then

|| Does this mean that it is possible to have variable types that
|| are not derived from Object?

No, I just think that while GetType is available in C#, it has, for some arbitrary (ie I can't fathom it :-)) reason, has been
removed from Interfaces in VB.
I hope this is of some use to you.

Regards,
Fergus
Nov 20 '05 #4
Bob,
In addition to what the others have stated.

IDictionary is an interface, in VB.NET interfaces do not gain anything from
System.Object.

Oddly enough in C# interfaces do gain the methods from System.Object. I
don't think C# views interfaces as inheriting from System.Object, as much as
it knows that any variable will have methods of System.Object available. As
you need an object (which inherits from System.Object) to implement any
Interface.

So in C# you can use GetType on a Interface variable, as Fergus
demonstrated.

Which is correctly I'm really not sure, as technically there is not a super
interface for Interfaces, such as System.Object is the super class for
Classes..

By super class & super interface I mean the most base Type that a Type
inherits from.
Does this mean that it is possible to have variable types that are not derived from Object? And if not, why aren't all variables treated as Objects? Yes. Remember System.Object is a class, while an Interface is an interface.
They are two distinct types of Types, very similar in many regards, but
distinct non the less.

You cannot have a Class in VB.NET inherit from an Interface, nor can you
have an Interface inherit from a Class. A Class Implements an Interface,
while an Interface can inherit other Interfaces.

Hope this helps
Jay

"Bob" <no*****@nospam .net> wrote in message
news:Ow******** **********@TK2M SFTNGP09.phx.gb l... This has been bugging me for a while now.

GetType isn't availble for variables decalred as interface types, I have to DirectCast(some variable, Object).

In example:

Sub SomeSub(ByVal Dictionary as IDictionary)
If Dictionary is Nothing Then Return
Dim o as Object = DirectCast(Dict ionary, Object)
If GetType(ISomeIn terface).IsAssi gnableFrom(o.Ge tType) Then
'<... some code...>
End If
End Sub

Does this mean that it is possible to have variable types that are not derived from Object? And if not, why aren't all variables treated as Objects?

Bob

Nov 20 '05 #5
Bob
It is allowed with Option Strict On, and I have yet to see such a conversion
fail under any circumstance at runtime; if you want to assert that the code
below does not 'make sense', you must provide an example where it causes an
exception.

But I do not believe one exists, as all vairables are either nothing or not
nothing. And if a variable is not nothing, if I understand the others' comments
correctly, it must be derived from Object.

Bob
GetType isn't availble for variables decalred as interface
types, I have to DirectCast(some variable, Object).


'DirectCast' to 'Object' doesn't make sense, because 'Object' is the more
general type.


Nov 20 '05 #6
Bob,
I agree with Herfried, it does not 'make sense' in that the DirectCast is
100% redundant!

Dim i As ICloneable
Dim o As Object

i = o

i = DirectCast(i, Object)

Both do the same thing, yet the statement with DirectCast is 20 characters
longer. Typing 20 extra characters 'does not make sense'.

Yes its allowed, I would be very surprised if it ever caused an exception.

However! is it really needed, does it really add any value to the statement?
I don't see that its needed or adds value, hence I agree with Herfried, it
does not make sense.

Remember when casting to Object or a base type, DirectCast is not needed.
Otherwise we could not use Object as a parameter type to allow any variable
to be passed.

Just a thought
Jay
"Bob" <no*****@nospam .net> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
It is allowed with Option Strict On, and I have yet to see such a conversion fail under any circumstance at runtime; if you want to assert that the code below does not 'make sense', you must provide an example where it causes an exception.

But I do not believe one exists, as all vairables are either nothing or not nothing. And if a variable is not nothing, if I understand the others' comments correctly, it must be derived from Object.

Bob
GetType isn't availble for variables decalred as interface
types, I have to DirectCast(some variable, Object).


'DirectCast' to 'Object' doesn't make sense, because 'Object' is the more general type.

Nov 20 '05 #7
Bob
Suppose you are stuck with the IClonable variable, it's coming in as part of the
signature of a method. Suppose now you need to determine if some other interface
is assignable to this variable's type. How would you do this without first using
the Object type either by casting or assignment?

Bob

"Jay B. Harlow [MVP - Outlook]" <Ja********@ema il.msn.com> wrote in message
news:%2******** *********@TK2MS FTNGP11.phx.gbl ...
Bob,
I agree with Herfried, it does not 'make sense' in that the DirectCast is
100% redundant!

Dim i As ICloneable
Dim o As Object

i = o

i = DirectCast(i, Object)

Both do the same thing, yet the statement with DirectCast is 20 characters
longer. Typing 20 extra characters 'does not make sense'.

Yes its allowed, I would be very surprised if it ever caused an exception.

However! is it really needed, does it really add any value to the statement?
I don't see that its needed or adds value, hence I agree with Herfried, it
does not make sense.

Remember when casting to Object or a base type, DirectCast is not needed.
Otherwise we could not use Object as a parameter type to allow any variable
to be passed.

Just a thought
Jay


Nov 20 '05 #8
Bob,
the Object type either by casting or assignment? This is key to what doesn't make sense is "casting OR assignment", what I am
saying does not make sense is using Casting on the Assignment to Object.

I use casting when I need casting otherwise I use simple assignment. Trust
me I need casting as I use Option Strict On!
Suppose now you need to determine if some other interface
is assignable to this variable's type. Huh?? Wouldn't it be far more beneficial to ask a variable if it supports
some type, rather than asking a type if it supports some type? In other
words rather then use Type.IsAssignab leFrom use a TypeOf Is expression
instead.

I would use 'Typof Is' expression:

Dim i As ICloneable
Dim x as whatever

If Typeof x is ICloneable Then
' do something with x,
' what I cannot tell by your statement
End If
How would you do this Normally I would use the 'Typeof Is' expression.

Dim i As ICloneable
If TypeOf i Is IComparable Then
Dim c As IComparable
c = DirectCast(i, IComparable)
End If

Remember that IComparable has no relationship to ICloneable (more
specifically IComparable does not inherit from ICloneable) & it is not
Object, hence I need to use the DirectCast as part of the assignment.

Going back to original post:

I would use something like:

Sub SomeSub(ByVal dictionary as IDictionary)
If dictionary is Nothing Then Return
If TypeOf dictionary Is ISomeInterface Then
Dim some As ISomeInterface
some = DirectCast(dict ionary, ISomeInterface)
'<... some code...>
End If
End Sub

Or if you are working with Type variables in a generic sense:

Private m_type As Type = GetType(ISomeIn terface)

Sub SomeSub(ByVal Dictionary as IDictionary)
If Dictionary is Nothing Then Return
Dim o as Object = Dictionary
If m_type.IsAssign ableFrom(o.GetT ype) Then
'<... some code...>
End If
End Sub

Notice there is no DirectCast on the assignment to Object (compiles without
it with Option Strict On)! However with the GetType(ISomeIn terface) in your
original post suggests you are not using Type variables.

Hope this helps
Jay

"Bob" <no*****@nospam .net> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. . Suppose you are stuck with the IClonable variable, it's coming in as part of the signature of a method. Suppose now you need to determine if some other interface is assignable to this variable's type. How would you do this without first using the Object type either by casting or assignment?

Bob

"Jay B. Harlow [MVP - Outlook]" <Ja********@ema il.msn.com> wrote in message news:%2******** *********@TK2MS FTNGP11.phx.gbl ...
Bob,
I agree with Herfried, it does not 'make sense' in that the DirectCast is 100% redundant!

Dim i As ICloneable
Dim o As Object

i = o

i = DirectCast(i, Object)

Both do the same thing, yet the statement with DirectCast is 20 characters longer. Typing 20 extra characters 'does not make sense'.

Yes its allowed, I would be very surprised if it ever caused an exception.
However! is it really needed, does it really add any value to the statement? I don't see that its needed or adds value, hence I agree with Herfried, it does not make sense.

Remember when casting to Object or a base type, DirectCast is not needed. Otherwise we could not use Object as a parameter type to allow any variable to be passed.

Just a thought
Jay

Nov 20 '05 #9
Bob,
I had it in my head that it would fail under certain conditions. But now I can't seem to find an example and you are right. If you think of it, let me know.

Remember that TypeOf allows you to check generically derived types match a
base type. While using GetType allows you to check for a specific type
(exclusive of derived types).

Dim fs As New IO.FileStream(" myfile.xml", FileMode.Open,
FileAccess.Read )
Dim isType As Boolean

' returns true, as fs is an IO.Stream & an IO.FileStream
isType = TypeOf fs Is IO.Stream

' returns false, as fs is not specifically an IO.Stream
isType = fs.GetType() is GetType(IO.Stre am)

TypeOf is my first choice, however the second is handy in some isolated
cases.

Hope this helps
Jay

"Bob" <no*****@nospam .net> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. .. Now why did I abandon TypeOf?

I had it in my head that it would fail under certain conditions. But now I can't seem to find an example and you are right. The code was redundant.

Oh well. That's par for the course for me.

Bob

Nov 20 '05 #10

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

Similar topics

2
3507
by: JohnnySparkles | last post by:
Hi everyone, I'm currently writing an application which uses the XmlSerializer class to serialize/deserialize objects to/from xml. Now when deserializing an XmlDocument back into the object, I'm using the System::Type::GetType(String* typeName) to create a Type* needed to construct the XmlSerializer. The typeName argument is taken from the XmlDocument and consists of the
5
3344
by: Ross A. Finlayson | last post by:
Hi, I'm scratching together an Access database. The development box is Office 95, the deployment box Office 2003. So anyways I am griping about forms and global variables. Say for example I'm adding a customer. The Customer fields are mostly foreign keys that refer to primary keys in other tables, left join instead of junction tables at this point. So, when I want to add a customer record, I also need to add records to the other...
2
1590
by: Razzerroo | last post by:
Still on my quest to convert my company's VB.NET code to C#. Here's the line I need to convert VB.NET System.Runtime.Remoting.RemotingServices.Connect(GetType(ISensor), strURL)) where ISensor is a public Interface in a referenced class library (DLL) and the strURL is a valid URI path.
17
2952
by: David Sobey | last post by:
hi - I have a class Node, with a child class Num, that inherits from Node. - I have a function "Evaluate" that takes two Nodes as an argument. - I call this function by sending it two "Num"'s. When i use GetType().ToSTring(), it seems to be aware that the arguments it recieved are in fact Nums, not Nodes. - How do I cast the arguments to Nums so I can use all the member functions and variables, without doing
30
6815
by: Javaman59 | last post by:
I come from a background of Ada and C++ programming, where it was considered good practice to explicitly initialize every variable. Now that I'm programming in C# I think that it would be best NOT to initialize class members, because every type has well defined initialization anyway. eg. class C
5
6301
by: Grande | last post by:
Hi all, I'm trying to use GetType to get an Interface, but it's not working? Is there a special way you have to do this, since it's an Interface (rather than a complete class)? Code: Type SpecDataType = SpecData.GetType(); string strTemp = "SCG.Persistence.Interfaces.Product.I" + SpecDataType.Name + "Dao";
7
7818
by: Sky | last post by:
I have been looking for a more powerful version of GetType(string) that will find the Type no matter what, and will work even if only supplied "{TypeName}", not the full "{TypeName},{AssemblyName}" As far as I know yet -- hence this question -- there is no 'one solution fits all', but instead there are several parts that have to be put together to check. What I have so far is, and would like as much feedback as possible to ensure I've...
0
2937
by: Flack | last post by:
Hey guys, Here is my scenario: I have a form and two dlls, call them ClassLibrary1.dll and Interfaces.dll. In my form I have the following: private Assembly m_assembly; private Type m_type; m_assembly = Assembly.LoadFrom("ClassLibrary1.dll"); m_type = m_assembly.GetType("ClassLibrary1.Class2");
2
3486
by: nibin | last post by:
pls help me it urgent i m facing a problem with my vb.net code this is the code equivalent in c# this is the interface........ ............................................................................................................... namespace x {. public interface ISection {
0
9645
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
10325
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
10147
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
10091
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
9950
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
8972
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
7499
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...
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.