473,378 Members | 1,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Generics and Casting - strange behaviour

I have a class "Validator" which can be cast to a Control. The code:
ValidTextBox t = (ValidTextBox)v;
works just fine.

However, because v doesn't descend from t, I can't use "is" or "as". I
did want a safe way of casting though - so I tried the following code:

public static T ConvertClass<T>(Validator myValidator) where T :
Control
{
T convertedObject;
try
{
convertedObject = (T)myValidator;
return convertedObject;
}
catch
{
return default(T);
}
}
and that worked fine. So I thought I'd make it more generic - no
reason this couldn't work for any two classes, after all.

public static T ConvertClass<T>(Object myObject)
{
T convertedObject;
try
{
convertedObject = (T)myObject;
return convertedObject;
}
catch
{
return default(T);
}
}

But that doesn't work. I get an exception thrown when it tries to
perform the cast, with the message:
Unable to cast object of type 'Validator' to type 'ValidTextBox'.
Which is clearly complete nonsense, as it will perform that cast if I
tell it to.

Anyone out there got an explanation?

Andy

Sep 19 '06 #1
6 1277
Andrew Ducker wrote:
I have a class "Validator" which can be cast to a Control. The code:
ValidTextBox t = (ValidTextBox)v;
works just fine.

However, because v doesn't descend from t, I can't use "is" or "as".
It sounds like there's a user-defined conversion from Validator to
ValidTextBox, which isn't used by is/as.

<snip>
But that doesn't work. I get an exception thrown when it tries to
perform the cast, with the message:
Unable to cast object of type 'Validator' to type 'ValidTextBox'.
Which is clearly complete nonsense, as it will perform that cast if I
tell it to.
Well, it's not really nonsense if there's a user-defined conversion
going on. The compiler is able to pick that up in the non-generic case,
and it doesn't actually create a cast as far as the IL is concerned -
it executes the conversion. Generics doesn't use explicit user-defined
conversion, and in CLR terms it *can't* cast from Validator to
ValidTextBox. The fact that a cast-expression in C# works doesn't mean
there's a valid CLR cast.

Jon

Sep 19 '06 #2
Jon Skeet [C# MVP] wrote:
Well, it's not really nonsense if there's a user-defined conversion
going on. The compiler is able to pick that up in the non-generic case,
and it doesn't actually create a cast as far as the IL is concerned -
it executes the conversion.
Aaah, so t = (ValidTextBox)v; can get translated into two different
sets of IL at compile time, depending on whether the conversion is
user-defined or not, and as it can't tell at compile time which one
it's going to need it assumes the straightforward cast is going to be
ok, which then throws an exception when it's not.

Is there a way for me to code around this - to try a straightforward
cast, then try a conversion, and if both fail then return null?

Andy

Sep 19 '06 #3
Andrew Ducker wrote:
Well, it's not really nonsense if there's a user-defined conversion
going on. The compiler is able to pick that up in the non-generic case,
and it doesn't actually create a cast as far as the IL is concerned -
it executes the conversion.

Aaah, so t = (ValidTextBox)v; can get translated into two different
sets of IL at compile time, depending on whether the conversion is
user-defined or not, and as it can't tell at compile time which one
it's going to need it assumes the straightforward cast is going to be
ok, which then throws an exception when it's not.
Yup.
Is there a way for me to code around this - to try a straightforward
cast, then try a conversion, and if both fail then return null?
The best thing to do, if you have access to Validator, is to have some
sort of generic conversion interface so it doesn't need to rely on
compile cleverness in the first place. I don't believe there's any way
of using user-defined conversions in a generic context.

Jon

Sep 19 '06 #4
Jon Skeet [C# MVP] wrote:
The best thing to do, if you have access to Validator, is to have some
sort of generic conversion interface so it doesn't need to rely on
compile cleverness in the first place. I don't believe there's any way
of using user-defined conversions in a generic context.
Well, it can clearly manage, when the constraints are right - otherwise
the first coding example wouldn't work. I'll have to take a further
look into it when I have more time.

Cheers for the advice,

Andy

Sep 19 '06 #5
Andrew Ducker wrote:
Jon Skeet [C# MVP] wrote:
The best thing to do, if you have access to Validator, is to have some
sort of generic conversion interface so it doesn't need to rely on
compile cleverness in the first place. I don't believe there's any way
of using user-defined conversions in a generic context.

Well, it can clearly manage, when the constraints are right - otherwise
the first coding example wouldn't work. I'll have to take a further
look into it when I have more time.
Ah - I've just looked at the samples again. The second sample wouldn't
have worked even without generics. User-defined conversions are applied
at compile-time, so if you did:

Object o = myValidator;
ValidTextBox vtb = (ValidTextBox) o;

you'd run into the same exception.

I'm frankly surprised that the user-defined conversion is applied in a
generic way to start with though. I might have to play around with
that. I tend to avoid user-defined conversions, to be honest... I like
casts to really be casts :)

Jon

Sep 19 '06 #6
Jon Skeet [C# MVP] wrote:
I'm frankly surprised that the user-defined conversion is applied in a
generic way to start with though. I might have to play around with
that. I tend to avoid user-defined conversions, to be honest... I like
casts to really be casts :)
Oh, me too, generally. I was trying to find a way around the lack of
multiple inheritance by having each of my subclasses of the subclasses
of Winforms.Control contain a private Validator object, and being
castable to it. That way it _looked_ like it was multiple inheritance
without actually being multiple inheritance.

It started off as a way of avoiding having to implement IValidator in
all of the Controls subclasses (I hate having multiple copies of code)
and kind of spread from there...

Doesn't quite work though, as you can see.

Andy D

Sep 20 '06 #7

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

Similar topics

13
by: Anders Borum | last post by:
Hello! Now that generics are introduces with the next version of C#, I was wondering what kind of performance gains we're going to see, when switching from e.g. the general hashtable to a...
4
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the...
5
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have...
11
by: hammad.awan_nospam | last post by:
Hello, I'm wondering if it's possible to do the following with Generics: Let's say I have a generic member variable as part of a generic class like this: List<DLinqQuery<TDataContext>>...
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
3
by: psyCK0 | last post by:
Hi all! I have a problem of casting generics to their base type. In the code below I first define a BaseList class that can hold items of any type that inherits from BaseItem. I then define a...
5
by: Lonifasiko | last post by:
Hi, I'm having quite a strange behaviour when using Generics classes and ComboBox controls in Winforms applications. Hope somebody has seen the same behaviour. Two combobox controls in my...
8
by: Tony Johansson | last post by:
Hello! I have read that in practice, casting proved to be several times faster than using a generic. So the main reason to use generics is not that the performance is better because that's...
101
by: Tinkertim | last post by:
Hi, I have often wondered if casting the return value of malloc() (or friends) actually helps anything, recent threads here suggest that it does not .. so I hope to find out. For instance : ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.