I have an interface that looks something like this:
public interface IFoo<Twhere T : IFoo<T{ ... }
Inside a class that looks something like this...
public class Bar<V{ ... }
....I would like to find out if V implements IFoo<V>. However, I can't
do this...
if (typeof(IFoo<V> ).IsAssignableF rom(typeof(V))) { ... }
....because it's circular: the compiler won't let us refer to IFoo<V>
because we don't know if V implements IFoo<V>. The best I can do is
this:
bool implementsInter face = true;
try
{
typeof(IFoo<>). MakeGenericType (typeof(V));
}
catch (ArgumentExcept ion)
{
// Oops! I guess not.
implementsInter face = false;
}
However, I don't get the impression this is the "right" way to do it.
I don't like the idea of catching an ArgumentExcepti on in general. Is
there some other way to do this? 4 1872
On Jun 5, 5:13 pm, Weeble <clockworksa... @gmail.comwrote :
<snip>
However, I don't get the impression this is the "right" way to do it.
I don't like the idea of catching an ArgumentExcepti on in general. Is
there some other way to do this?
You could get all the interfaces that the type implements (potentially
recursively). For each of them, see if the generic type ==
typeof(IFoo<>), and then check the generic type argument to see if
it's typeof(V).
Jon
So working from Jon's idea, perhaps something like the code below would
work?
---------------------------
using System;
using System.Collecti ons.Generic;
using System.Text;
public interface IFoo<Twhere T : IFoo<T>
{
}
class SomeClass : IFoo<SomeClass>
{
}
class Bar<V>
{
public static bool ImplementsInter face()
{
string interfaceName = typeof(IFoo<>). Name;
Type theInterface = typeof(V).GetIn terface(interfa ceName);
if (theInterface != null)
{
Type deff = theInterface.Ge tGenericTypeDef inition();
return (deff == typeof(IFoo<>)) ;
}
else
return false;
}
}
class Program
{
static void Main(string[] args)
{
bool result1 = Bar<SomeClass>. ImplementsInter face();
Console.WriteLi ne(result1.ToSt ring());
bool result2 = Bar<string>.Imp lementsInterfac e();
Console.WriteLi ne(result2.ToSt ring());
Console.Read();
}
}
---------------------------
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:2e******** *************** ***********@i76 g2000hsf.google groups.com...
On Jun 5, 5:13 pm, Weeble <clockworksa... @gmail.comwrote :
<snip>
>However, I don't get the impression this is the "right" way to do it. I don't like the idea of catching an ArgumentExcepti on in general. Is there some other way to do this?
You could get all the interfaces that the type implements (potentially
recursively). For each of them, see if the generic type ==
typeof(IFoo<>), and then check the generic type argument to see if
it's typeof(V).
Jon
On Jun 6, 12:53 am, "Rene" <a...@b.comwrot e:
So working from Jon's idea, perhaps something like the code below would
work?
[snip]
That's great, thank you both! I think to be safe I'd still need to
check the generic type argument, otherwise it could break like this:
class CheatClass : SomeClass { }
Which gives {Bar<CheatClass >.ImplementsInt erface()==True} , which isn't
quite what I want to check. But it's clear how to handle that, so
thanks!
Of course, now there's the question of whether there's a better way
than wanton use of reflection to get out of the generic tangle that
resulted in this. Sadly it's not easy to show an isolated example, so
I think I'll leave it for another time. In general terms, would people
say that *sometimes* it's better just to suffer a bit of typecasting
rather than try to preserve types with complex application of
generics, or is there *always* a good generic solution that guarantees
type-safety at compile-time?
On Jun 6, 3:14 pm, Weeble <clockworksa... @gmail.comwrote :
<snip>
Of course, now there's the question of whether there's a better way
than wanton use of reflection to get out of the generic tangle that
resulted in this. Sadly it's not easy to show an isolated example, so
I think I'll leave it for another time. In general terms, would people
say that *sometimes* it's better just to suffer a bit of typecasting
rather than try to preserve types with complex application of
generics, or is there *always* a good generic solution that guarantees
type-safety at compile-time?
The former. Things will improve slightly if/when C# 4 includes generic
variance, but it'll never go away entirely. It's always worth *trying*
to see if there's a generic solution to solve the problem, but it
won't always happen.
Jon This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Bentley |
last post by:
John Bentley:
INTRO
The phrase "decimal number" within a programming context is ambiguous. It could
refer to the decimal datatype or the related but separate concept of a generic
decimal number. "Decimal Number" sometimes serves to distinguish Base 10
numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal
Number" serves to differentiate a number from an integer. For the rest of this
post I shall only use either...
|
by: Walter L. Preuninger II |
last post by:
I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.
int main(void)
{
int i=7;
char *s="/etc/filesystems";
generic(i);
|
by: Sathyaish |
last post by:
I wanted to practice some Linked List stuff, so I set out to create a
linked list. The plan was to create the following:
(1) A linked list class in Visual Basic
(2) A non-class based linked list using functions in C
(3) A linked list class in C++
I started with Visual Basic and I wrote an IList interface that I
wanted my list to implement. When I had started, somehow I thought
this time, I'd first use a collection as the ingredient,...
|
by: Leszek Taratuta |
last post by:
Hello,
I have the following code:
// Load the MenuBar.ascx user control. The control defines SavePropertyEvent
event.
UserControl ctrl =
(UserControl)Page.LoadControl("~/MyApp/Controls/MenuBar.ascx");
// Get type information of the loaded user control.
|
by: Tosch |
last post by:
I have written an interface, let's call it AddinInterface1.
At some stage I had to add more properties to the interface.
So I wrote a new interface, AddinInterface2 which inherits AddinInterface1.
My application tries to load DLLs which implement AddinInterface1. If I have a DLL which implements AddinInterface2 I have to set some additional
properties.
How can I determine in my application which interface is implemented in a DLL?
Tosch
| |
by: Dave Booker |
last post by:
Am I missing something here? It looks like the generic Queue<T> implements
Enumerable<T> and ICollection but not ICollection<T>. (I want to use it in
an interface that wants an ICollection<T>.)
Is there a reason for this, or is it just an oversight in .NET 2.0?
Is there a computationally easy way to cast/convert a Queue<T> to an
ICollection<T>?
|
by: mps |
last post by:
I want to define a class that has a generic parameter that is itself a
generic class. For example, if I have a generic IQueue<Tinterface, and
class A wants to make use of a generic class that implements IQueue<Tfor
all types T (so it can make use of queues of various object types
internally). As useful as this is, it doesn't seem possible. The natural (but
illegal) notation would be something like
class A<QueueClasswhere QueueClass :...
|
by: =?Utf-8?B?R3JlZw==?= |
last post by:
I am a newbie to WCF so please forgive if this is an obvious question.
I have the following.
(Service contract) IEmployee
public interface IEmployee
{
List<EmployeeGetEmployeeByID(string employeeID);
|
by: PJ6 |
last post by:
I'd like to be able to declare a function where it always returns the type
of the inheritor. To show this in as simple an example that I can think of,
where MyClassType is a reflexive generic type -
Public Class BaseClass
Public Function TestFunction() as MyClassType
Return Me
End Function
End Class
|
by: tadmill |
last post by:
Is it possible for a class that accepts a generic type, to re-create
another instance of itself with a property type of the passed class?
ex.
public class SomeClass<T>
{
private PropertyInfo propInfos;
private Type objectType = typeof(T);
public SomeClass()
|
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...
| |
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...
|
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...
|
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,...
|
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...
|
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...
|
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...
| |
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
| |