473,508 Members | 2,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on Casting to a BaseType

I created a control that derives from the System.Windows.Forms.Control
namespace.
I then created an interface to which this new control must adhere, so that I
could require future controls to provide certain functionality.

In my form code, I'm not going to be sure of what types of controls the form
will be using until run-time. So, I created an array of controls, all cast
as Control. This all works fine, so far.

Now, in the form code, I figured out how to determine whether or not the
control I'm currently accessing from the control array implements my
interface. I did this using a call to
currentControl.GetType().GetInterface("InterfaceNa me"). However, because
currentControl is reference as a System.Windows.Forms.Control, rather than
as a MyControl, I can't cast to the interface.

Does anyone know a way of casting to the interface and accessing the
properties that the interface defines? Obviously, it's going to be very
counter-productive to have to create a whole set of custom controls that
merely inherit from the various Windows forms controls, just so that I can
make sure that all of the implement my interface.

The closest MSDN help article I could find is this:
<ms-help://MS.VSCC/MS.MSDNVS/vbcon/html/vbconwhenshouldiimplementinterfacesi
nmycomponent.htm>, and indicates code like the following:

BusinessAccount business = new BusinessAccount();
IAccount account = business;
account.PostInterest();

Here's some sample code:

using System.Windows.Forms

Control[] controlArray;

..... get controls into the array, from various sources....

if (controlArray[i].GetType().GetInterface( "MyInterface", true ) != null )
{
MyInterface interfaceInst = controlArray[i];
int propertyValue = interfaceInst.Property1;
}

Unfortunately, this code throws an InvalidCastException. Using a casting
statement (i.e. "MyInterface interfaceInst = (MyInterface)
controlArray[i];") doesn't work, either.

Anyone have any ideas?

Thanks,

Chris
Nov 15 '05 #1
4 1843
Now, in the form code, I figured out how to determine whether or not the
control I'm currently accessing from the control array implements my
interface. I did this using a call to
currentControl.GetType().GetInterface("InterfaceN ame").
It would be eaiser and faster to do

if ( currentControl is InterfaceName )

However, because
currentControl is reference as a System.Windows.Forms.Control, rather than
as a MyControl, I can't cast to the interface.
If a cast succeeds or not depends on the actual type of the object,
not the type of the reference you hold to it. So if the the interface
is supported, the cast should succeed even though you hold a Control
reference to it.

Unfortunately, this code throws an InvalidCastException. Using a casting
statement (i.e. "MyInterface interfaceInst = (MyInterface)
controlArray[i];") doesn't work, either.

Anyone have any ideas?


In that case the class apparently doesn't implement the interface. I'm
not sure why that might be. You haven't used "copy and paste" code
reuse, have you? In other words, the implementing class and the
consuming class are using the same definition of the interface, right?

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 15 '05 #2
Thanks for responding!

I tried using the "is" statement, and it doesn't work; after reading up on
the keyword, I'm guessing that it's due to the same reason that's throwing
the InvalidCastException when I try to cast.

Regarding the casting, and the implementation of the interface, as far as I
can tell, I've implemented the same interface in both classes. I _have_
implemented two interfaces, the second of which inherits from the first.
The code is similar to the following (minus obvious references to control
assemblies, etc.):

namespace MyApp.MyInterfaces
{
public interface IMyFirstInterface
{
int MyIntValueProp { get; set; }
object[] MyObjArrayProp { get; set; }
string[] MyStrArrayProp { get; set; }
}
}

namespace MyApp.MyInterfaces
{
public interface IMySecondInterface : IMyFirstInterface
{
MySecondIntProp { get; set; }
string MyStrProp { get; set; }
}
}

using MyApp.MyInterfaces;
using System.Windows.Forms;
namespace MyApp.MyClasses
{
public class MyControlClass : System.Windows.Form.Control,
IMySecondInterface
{
public MyControlClass()
{
// some constructor code
}

// some other code
}

Do you see any problems with this implementation?

"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
Now, in the form code, I figured out how to determine whether or not the
control I'm currently accessing from the control array implements my
interface. I did this using a call to
currentControl.GetType().GetInterface("InterfaceN ame").


It would be eaiser and faster to do

if ( currentControl is InterfaceName )

However, because
currentControl is reference as a System.Windows.Forms.Control, rather thanas a MyControl, I can't cast to the interface.


If a cast succeeds or not depends on the actual type of the object,
not the type of the reference you hold to it. So if the the interface
is supported, the cast should succeed even though you hold a Control
reference to it.

Unfortunately, this code throws an InvalidCastException. Using a casting
statement (i.e. "MyInterface interfaceInst = (MyInterface)
controlArray[i];") doesn't work, either.

Anyone have any ideas?


In that case the class apparently doesn't implement the interface. I'm
not sure why that might be. You haven't used "copy and paste" code
reuse, have you? In other words, the implementing class and the
consuming class are using the same definition of the interface, right?

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.

Nov 15 '05 #3
Hi Chris,
In addition to Mattias's question:
1. are you sure that all objects in controllArray are implementing the
interfaces?
2. Here in the group somewhere I have read something interesting about
"is" keyword, i.e. if you are planning to use "is" only as preparation
to a cast, its better to use "as", so maybe you should try:

instead

Control[] controlArray;

.... get controls into the array, from various sources....

if (controlArray[i].GetType().GetInterface( "MyInterface", true ) != null )
{
MyInterface interfaceInst = controlArray[i];
int propertyValue = interfaceInst.Property1;
}


try this:

MyInterface obj = controlArray[i] as MyInterface;
int propertyValue;
if (obj != null)
{
propertyValue = obj.Property1;
}

Sunny
Nov 15 '05 #4
Chris,
Do you see any problems with this implementation?


No, other than the fact that the MySecondIntProp is lacking a return
type, but I assume that's just a typo.

Is the interface defined in a separate assembly? If so, double check
that you're referencing the same version of that assembly.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 15 '05 #5

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

Similar topics

3
1612
by: Rhino | last post by:
I am trying to figure out if a UDF can accept a UDT (User-defined Distinct Type, *not* structured type) as one of its parameters. I'm running DB2 for Linux, Unix, and Windows V8.2 (FP 8) on Windows...
2
2549
by: Zac | last post by:
Alright anyone who has 2c throw it in... I am working through a custom xml serializer and have come upon a conundrum, given our class design. The interface implemented on the base class (base...
4
8347
by: Alicia | last post by:
Hi all, I have a problem with an Enum and Reflection. I am using an Xml and Reflection to create some controls, and to set their properties. All goes well until I encounter one property which is...
3
1383
by: Abelardo Vacca | last post by:
Hello, Is there a way to cast to another type when all we have is the System.Type. Say, if we have: Class MyBaseClass; Class MyDerivedClass:MyBaseClass; instead of: MyDerivedClass...
5
2134
by: Simon | last post by:
Hi folks, Take the following scenario: public class BaseType { } public class DerivedTypeA : BaseType {
7
564
by: hello_world | last post by:
Let's say I have the following class hierarchy: A: B B: C I would like a means to test whether class C is a 'descendant' of class A (or A is the 'ancestor' of C). If c is the instance of C,...
3
1564
by: Anonymous | last post by:
I want to be able to restrict the set of classes for which a template class can be instantiated (i.e enforce that all instantiation MUST be for classes taht derive from a base type BaseType). ...
0
903
by: LieWait | last post by:
've got some code that is trolling through and assembly looking for methods that have parameters whose BaseType is DataSet (they are strongly-typed DataSets). .ParameterType.BaseType is always...
7
289
by: z71mdridin | last post by:
I have three classes: Public MustInherit Class Animal Public MustOverride Function speak() As String End Class Public Class dog Inherits Animal Public Overrides Function speak() As String...
0
7118
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...
0
7379
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...
0
5625
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
5049
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
4706
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
3192
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...
0
3180
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1550
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 ...
0
415
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...

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.