I was wondering if someone could think of a nice workaround for not being able to add an implicit cast operator, for object, on your own class. The following example illustrates the kind of code I would like
public class Response
{
public string Contents { get; set; }
public static implicit operator Response(object source)
{
return new Response { Contents = source.ToString(); };
}
}
This won't compile because it upsets the C# compiler and it tells me
user-defined conversions to or from a base class are not allowed
Turning response into Response and doing
public static implicit operator Response<T>(T source)
is unfortunately not an option. My guess is going to be no, but could anyone think of a nice workaround/hack to get this to work. I would love to be able to do
public Response Foo()
{
return new Bar();
}
and end up with a Response.Contents that said Whatever.Namespace.Bar
I'm not a fan of implicit conversions like this - other answers have explained why this isn't allowed. One option to make the conversion easy if you really don't want constructor calls in your code is via an extension method:
public static ResponseExtensions
{
public static Response ToResponse(this object source)
{
return new Response { Contents = source.ToString(); };
}
}
Then you can at least have:
public Response Foo()
{
return new Bar().ToResponse();
}
Generally I'm wary of extension methods on object, mind you... does it really make sense to convert any object at all into a Response?
Think about
Response r = CreateSomeExampleResponse();
Response r2 = r;
having the user-defined conversion defined for any of the base classes of Response. What shall happen in the example? The second assignment is ambiguous:
will r2 reference to a new Response instance with Content set to r.ToString() or
will r2 reference to the instance ris referring to?
(okay or will R2 have to do anything with some force, light sabers and stuff)
We can even expand our thoughts to subclasses of Response that are certainly allowed and correct because of polymorphy.
I guess there is no way to accomplish this. Moreover your code perhaps would be nicer to look at, but it would be far away from being well understandable.
I suggest using a the dynamic type instead of implicit object casting. It's basically what dynamic is, seemingly.
Moreover, see this question for the debate on conversions to or from a base class: User-defined conversion operator from base class
However, this was a very specific case where the cast was really needed. You might need to rethink your design instead.
there is no solution to your problem with your costraints. This is clearly specified in the error: user-defined conversions to or from a base class are not allowed. Since every class inherits object, you have your answer. Inheritance from Response to object means that all instances of Response are also instances of object!!! An implicit cast from object to Response means that every object is a Response, which is a nonsense!!!
In your case, could you simply define a Bar -> Response operator?
When you perform type conversion, you must be able to define a conversion algorithm someway. Can you tell me how are you supposed to convert an object, the most generic type in .NET that has only a hash code and a string representation, into an object of a specific type?
Related
I'm working with a class library called DDay ICal.
It is a C# wrapper for the iCalendar System implemented in Outlook Calendars, and many many many more systems.
My question is derived from some work I was doing with this system.
There are 3 objects in question here
IRecurrencePattern - Interface
RecurrencePattern - Implementation of IRecurrencePattern Interface
DbRecurPatt - Custom Class that has an implicit type operator
IRecurrencePattern: Not all code is shown
public interface IRecurrencePattern
{
string Data { get; set; }
}
RecurrencePattern: Not all code is shown
public class RecurrencePattern : IRecurrencePattern
{
public string Data { get; set; }
}
DbRecurPatt: Not all code is shown
public class DbRecurPatt
{
public string Name { get; set; }
public string Description { get; set; }
public static implicit operator RecurrencePattern(DbRecurPatt obj)
{
return new RecurrencePattern() { Data = $"{Name} - {Description}" };
}
}
The confusing part: Through out DDay.ICal system they are using ILists to contain a collection of Recurrence patterns for each event in the calendar, the custom class is used to fetch information from a database and then it is cast to the Recurrence Pattern through the implicit type conversion operator.
But in the code, I noticed it kept crashing when converting to the List<IRecurrencePattern> from a List<DbRecurPatt> I realized that I needed to convert to RecurrencePattern, then Convert to IRecurrencePattern (as there are other classes that implement IRecurrencePattern differently that are also included in the collection
var unsorted = new List<DbRecurPatt>{ new DbRecurPatt(), new DbRecurPatt() };
var sorted = unsorted.Select(t => (IRecurrencePattern)t);
The above code does not work, it throws an error on IRecurrencePattern.
var sorted = unsorted.Select(t => (IRecurrencePattern)(RecurrencePattern)t);
This does work tho, so the question I have is; Why does the first one not work?
(And is there a way to improve this method?)
I believe it might be because the implicit operator is on the RecurrencePattern object and not the interface, is this correct? (I'm new to interfaces and implicit operators)
You have basically asked the compiler to do this:
I have this: DbRecurPatt
I want this: IRecurrencePattern
Please figure out a way to get from point 1. to point 2.
The compiler, even though it may only have one choice, does not allow you to do this. The cast operator specifically says that DbRecurPatt can be converted to a RecurrencePattern, not to a IRecurrencePattern.
The compiler only checks if one of the two types involved specifies a rule on how to convert from one to the other, it does not allow intermediary steps.
Since no operator has been defined that allows DbRecurPatt to be converted directly to IRecurrencePattern, the compiler will compile this as a hard cast, reinterpreting the reference as a reference through an interface, which will fail at runtime.
So, the next question would be this: How can I then do this? And the answer is you can't.
The compiler does not allow you to define a user-defined conversion operator to or from an interface. A different question here on Stack Overflow has more information.
If you try to define such an operator:
public static implicit operator IRecurrencePattern(DbRecurPatt obj)
{
return new RecurrencePattern() { Data = $"{obj.Name} - {obj.Description}" };
}
The compiler will say this:
CS0552
'DbRecurPatt.implicit operator IRecurrencePattern(DbRecurPatt)': user-defined conversions to or from an interface are not allowed
Why does the first one not work?
Because you're asking the runtime for two implicit conversions - one to RecurrencePattern and one to IRecurrencePattern. The runtime will only look for a direct implicit relationship - it will not scan all possible routes to get you ask it to go. Suppose there were multiple implicit conversions to different types of classes that implement IRecurrencePattern. Which one would the runtime choose? Instead it forces you to specify individual casts.
This is documented in Section 6.4.3 of the C# Language specification:
Evaluation of a user-defined conversion never involves more than one
user-defined or lifted conversion operator. In other words, a
conversion from type S to type T will never first execute a
user-defined conversion from S to X and then execute a user-defined
conversion from X to T.
As others have pointed out already, you can't make a direct jump from DbRecurPatt to IRecurrencePattern. This is why you end up with this very ugly double cast:
var sorted = unsorted.Select(t => (IRecurrencePattern)(RecurrencePattern)t);
But, for completeness' sake, it should be mentioned that it is possible to go from a DbRecurPatt to a IRecurrencePattern without any casts with your current design. It's just that to do so, you need to split your expression into multiple statements, and by doing so, the code does become considerably uglier.
Still, it's good to know that you can do this without any casts:
var sorted = unsorted.Select( t => {
RecurrencePattern recurrencePattern = t; // no cast
IRecurrencePattern recurrencePatternInterface = recurrencePattern; // no cast here either
return recurrencePatternInterface;
});
EDIT
Credit to Bill Nadeau's answer for the idea. You can also benefit from implicit conversion and its compile time guarantees while keeping the code pretty elegant by writing it this way instead:
var sorted = unsorted
.Select<DbRecurPatt, RecurrencePattern>(t => t) // implicit conversion - no cast
.Select<RecurrencePattern, IRecurrencePattern>(t => t); // implicit conversion - no cast
There's another path to accomplish what you want. Specifically mark your generic arguments on your method calls instead of letting the compiler infer your generic arguments. You will still avoid casting, and it may be a little less verbose than some of the other options. The only caveat is you must include an additional Linq statement, which will resolve your list, if that matters.
var sorted = unsorted
.Select<DbRecurPatt, RecurrencePattern>(t => t)
.ToList<IRecurrencePattern>();
You could also combine this answer with sstan's to avoid the extra Linq statement.
... and to answer your final question about the implicit operator - no, you can't define an implicit operator on an interface. That topic is covered in more detail in this question:
implicit operator using interfaces
I have a generic function like this:
private LOCAL_TYPE RemoteToLocal<LOCAL_TYPE>(RemoteObjectBaseType remoteObject)
where LOCAL_TYPE: EntityBase
{
Type t = typeof(LOCAL_TYPE);
if (t == typeof(FavoritePlace))
{
return new FavoritePlace(remoteObject as RemotePlaceType1);
}
}
Where EntityBase is non-abstract class. FavoritePlace class is inherited from EntityBase.
However, I'm getting an error:
Cannot implicitly convert type Common.Model.FavoritePlace to 'LOCAL_TYPE'.
That makes me wonder: FavoritePlace is a child of EntityBase, and LOCAL_TYPE is constrained to be of type EntityBase. Why cannot the conversion happen? I'm probably missing something important here.
EDIT: Okay, based on current answers and some experiment I've found another workaround, which is to do following conversion:
if (t == typeof(FavoritePlace))
{
return (LOCAL_TYPE)(EntityBase)new FavoritePlace(remoteObject);
}
Now compiler is happy. But I'm just wondering, if such conversion is possible from compiler's perspective, why direct conversion to LOCAL_TYPE is not? Isn't is convertible to relationship transitive?
The problem is that FavoritePlace is not necessarily the type of LOCAL_TYPE.
If you have
class OtherEntity : EntityBase { }
then you can't return FavoritePlace when calling
var entity = RemoteToLocal<OtherEntity>(remoteObject);
If you know the conversion is safe you can get around it with a cast:
return (LOCAL_TYPE)(object)new FavoritePlace(remoteObject as RemotePlaceType1);
Although you have established through run-time code that LOCAL_TYPE is in fact FavoritePlace, the compiler does not have the same knowledge statically. The compiler expects you to return an object of type LOCAL_TYPE, matching exactly the type parameter of the method.
Thinks of this situation: someone makes the following call -
var res = RemoteToLocal<MostHatedPlace>(remoteObj); // MostHatedPlace derives from EntityBase
Now you're inside RemoteToLocal, you go through some conditions, and now it's time to return the result. You call
return new FavoritePlace(remoteObject as RemotePlaceType1);
You know that this branch in code is impossible to reach, because there is a run-time check guarding you from that:
if (t == typeof(FavoritePlace)) {
....
}
However, the compiler must assume that reaching this return statement is possible, which would be an error in cases when LOCAL_TYPE is not a FavoritePlace.
You may want to reconsider the use of generics here: from the code snippet it appears that you need the generic argument to avoid type-casting the result to the desired type in the caller. However, the caller would then need to perform an additional check to see if the conversion inside your RemoteToLocal has succeeded. In this case, a method
private EntityBase RemoteToLocal(RemoteObjectBaseType remoteObject) {
....
}
may be equally suited to the task, because it would be free of conversions that trick the compiler, and the structure of the calling code would remain the same.
I expect there's one of two answers to this, either impossible or extremely simple and I've overlooked the obvious Google query.
The underlying issue is that I have a generic object being passed in via an EventHandler that boxes the object and obfuscates the true type; only at runtime do I know what the object is.
Admittedly the dynamic keyword can get around the issue, but I'd like to not lose IntelliSense and everything if I can avoid it. Plus, it doesn't solve not knowing what each of the properties of the generic object are without massive amounts of reflection.
EDIT: The idea is to be able to determine the true type of the an object in a method parameter, and then cast that object as it's true type without knowing it in advance. This is but a simplified example. Boxed may have been the wrong term.
An example:
public class Program
{
static void Main(string[] args)
{
var container = new Container<Containee>(
new Containee
{
Property1 = Guid.NewGuid(),
Property2 = "I'm a property!",
Property3 = DateTime.Now
}
);
var boxed = (object)container;
var originalType = boxed.GetType();
// DOES NOT COMPILE: would like an operation like this
// EDIT: Request for more detail
var actualType = boxed as originalType;
actualType.Entity.Property2 = "But I like this better.";
}
}
public class Containee
{
public Guid Property1 { get; set; }
public string Property2 { get; set; }
public DateTime Property3 { get; set; }
}
public class Container<T>
{
public Container(T entity)
{
Entity = entity;
}
public T Entity { get; internal set; }
}
Clearly that won't compile, as there's not really a way to cast as a variable. However, I'm hoping there's a way to get a reference to the actual object and type, or at least, a way to dynamically re-create the type.
I expect there's something simple I'm overlooking, or a better way to get around it in general. The point is to be able to wrap any object in the container, and figure out later what it was.
The idea is to be able to determine the true type of the an object in a method parameter
That's easy enough (and you're already doing it).
Type actualType = param.GetType();
That will get you the actual concrete type of the object
and then cast that object as it's true type
This is where things come off the rails a bit. The casting operator in C# (usage of which is what people refer to as "casting") can do two things:
Use type-specific explicit conversions to create a new object by applying the conversion to the existing object (note that this is a new reference that is created; the original object's type is never changed)
Allow the developer to reference an object as a type that is at a different level in its inheritance hierarchy than is currently provided (or an interface that is implemented on a type that is lower in the hierarchy than is currently referenced)
In your case, the first option is right out; the casting operator, like all operators, is not polymorphic. That is, an operator is only applied if it is defined on the type that is being referenced, not the object that's being referenced. If you'd like further clarification on this, let me know, but I don't think it's germane to your question so I'm not going to go into it further unless asked.
The second option is the only option that could realistically apply to you, but consider the only two reasons you would want to do this:
So that you can refer to the object as a specific concrete type that is at a lower level than is currently provided (in your case, your object is an object, so that's pretty much as high as it goes)
So that you can refer to an object as a type that is higher in the hierarchy so that you can bypass hidden (but not overridden) members.
(The vast majority of casts are for reason #1)
The reason you would want to use either of those options is so that you can have a strongly-typed object and use the various members defined on that type. But all of these things only apply to types that you know when you're writing the code. It doesn't make sense to cast to a type that is unknown at compile time, as casting doesn't do anything to the actual object (it is, and shall remain, its true type; the only thing that changes is the type of the variable by which you reference the object).
If you can provide a further fleshed-out example of what you're actually trying to do (complete with code as you'd either like or expect it to work), I might be able to provide something modeled a little closer to what you want, but as it's described this is as specific as I can get.
First of all: That's not "boxing". Boxing is for value types, like structs.
Second of all: What you probably need is either:
Compile-time reflection, which C# doesn't have
Dynamic code generation, which you can do (painfully) with Reflection.Emit.
Third of all: Your sample code does variable1 as variable2, which doesn't really make sense. :\ What are you intending to do after that? Perhaps there's a better way.
You could use dynamic:
dynamic actualType = boxed;
actualType.Entity.Property2 = "But I like this better.";
This should compile and work.
var actualType = boxed as originalType;
Just so we're on the same page, let me explain why this is impossible.
var is a compile time construct. It is, identical to declaring the variable with the proper type straight off. Besides being easier to type, it's main use is for anonymous types which, as implied, have no names.
Anyway, to get to the meat of your question, your best bet is to use Dynamic code generation, either with Reflection.Emit or CodeDom (the latter is much easier to understand if you don't know ILASM, but is much slower).
Depending on what you actually want to do, you might be able to get away with something like
if(someObject is Container<Containee>) {
var container = (Container<Containee>)someObject;
//...
}
But, if you can expect literally any type, well... good luck.
The underlying issue is that I have a
generic object being passed in via an
EventHandler that boxes the object and
obfuscates the true type; only at
runtime do I know what the object is.
How do you want to handle it, if the type is only known at runtime? You can't call any specific class methods because you won't know the exact type anyway, unless all objects share some set of methods which can be extracted as interface.
Basically, you have several options:
Use is and do different things for different types:
object value = GetValue ();
if (value is Program)
((Program)value).Run ();
else if (value is Animal)
((Animal)value).Run ();
If all possible types are supposed to share a set of operations, use an interface:
object value = GetValue ();
IRunnable runnable = (IRunnable)value;
runnable.Run ();
Rephrase your question and extend your sample with how you see it working after you've done the ‘magical casting’. This would give us the idea what you're trying to accomplish.
Given a couple types like this:
interface I {}
class C : I {}
How can I do a static type cast? By this I mean: how can I change its type in a way that gets checked at compile time?
In C++ you can do static_cast<I*>(c). In C# the best I can do is create a temporary variable of the alternate type and try to assign it:
var c = new C();
I i = c; // statically checked
But this prevents fluent programming. I have to create a new variable just to do the type check. So I've settled on something like this:
class C : I
{
public I I { get { return this; } }
}
Now I can statically convert C to I by just calling c.I.
Is there a better way to do this in C#?
(In case anyone's wondering why I want to do this, it's because I use explicit interface implementations, and calling one of those from within another member function requires a cast to the interface type first, otherwise the compiler can't find the method.)
UPDATE
Another option I came up with is an object extension:
public static class ObjectExtensions
{
[DebuggerStepThrough]
public static T StaticTo<T>(this T o)
{
return o;
}
}
So ((I)c).Doit() could also be c.StaticTo<I>().Doit(). Hmm...probably will still stick with the simple cast. Figured I'd post this other option anyway.
Simply cast it:
(I)c
Edit Example:
var c = new C();
((I)c).MethodOnI();
Write an extension method that uses the trick you mentioned in your UPDATE:
public static class ObjectExtensions
{
public static T StaticCast<T>(this T o) => o;
}
To use:
things.StaticCast<IEnumerable>().GetEnumerator();
If things is, e.g., IEnumerable<object>, this compiles. If things is object, it fails.
// Compiles (because IEnumerable<char> is known at compiletime
// to be IEnumerable too).
"adsf".StaticCast<IEnumerable>().GetEnumerator();
// error CS1929: 'object' does not contain a definition for 'StaticCast'
// and the best extension method overload
// 'ObjectExtensions.StaticCast<IEnumerable>(IEnumerable)'
// requires a receiver of type 'IEnumerable'
new object().StaticCast<IEnumerable>().GetEnumerator();
Why Use a Static Cast?
One common practice during refactoring is to go ahead and make your changes and then verify that your changes have not caused any regressions. You can detect regressions in various ways and at various stages. For example, some types of refactoring may result in API changes/breakage and require refactoring other parts of the codebase.
If one part of your code expects to receive a type (ClassA) that should be known at compiletime to implement an interface (IInterfaceA) and that code wants to access interface members directly, it may have to cast down to the interface type to, e.g., access explicitly implemented interface members. If, after refactoring, ClassA no longer implements IIterfaceA, you get different types of errors depending on how you casted down to the interface:
C-style cast: ((IInterfaceA)MethodReturningClassA()).Act(); would suddenly become a runtime cast and throw a runtime error.
Assigning to an explicitly-typed variable: IInterfaceA a = MethodReturningClassA(); a.Act(); would raise a compiletime error.
Using the static_cast<T>-like extension method: MethodReturningClassA().StaticCast<IInterfaceA>().Act(); would raise a compiletime error.
If you expected your cast to be a downcast and to be verifiable at compiletime, then you should use a casting method that forces compiletime verification. This makes the intentions of the code’s original developer to write typesafe code clear. And writing typesafe code has the benefit of being more verifiable at compiletime. By doing a little bit of work to clarify your intention to opt into typesafety to both other developers, yourself, and the compiler, you magically get the compiler’s help in verifying your code and can catch repercussions of refactoring earlier (at compiletime) than later (such as a runtime crash if your code didn’t happen to have full test coverage).
var c = new C();
I i = c; // statically checked
equals to
I i = new C();
If you're really just looking for a way to see if an object implements a specific type, you should use as.
I i = whatever as i;
if (i == null) // It wasn't
Otherwise, you just cast it. (There aren't really multiple types of casting in .NET like there are in C++ -- unless you get deeper than most people need to, but then it's more about WeakReference and such things.)
I i = (I)c;
If you're just looking for a convenient way to turn anything implementing I into an I, then you could use an extension method or something similar.
public static I ToI(this I #this)
{
return #this;
}
I have a object:
ExampleClass ex = new ExampleClass();
And:
Type TargetType
I would like to cast ex to type described by TargetType like this:
Object o = (TargetType) ex;
But when I do this I get:
The type or namespace name 't' could
not be found
So how to do this? Am I missing something obious here?
Update:
I would like to obtain something like this:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
private otherClass;
And because I will have many properties like this I would like do this:
public CustomClass MyClassOuter
{
get
{
return (GetThisPropertyType()) otherClass;
}
}
private SomeOtherTypeClass otherClass;
Context:
Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet.
It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type.
All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".
For example:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];
}
}
}
And ok - I can make many properties like this one above - but there is 2 problems:
1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.
2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.
That's why I would like to do something like this:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];
}
}
}
And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).
Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.
Object o = (TargetType) ex;
This code is useless. You might have a type on the right but it's still only an object on the left side. You can't use functionality specific to TargetType like this.
This is how you can invoke a method of an unknown object of a given type:
object myObject = new UnknownType();
Type t = typeof(UnknownType); // myObject.GetType() would also work
MethodInfo sayHelloMethod = t.GetMethod("SayHello");
sayHelloMethod.Invoke(myObject, null);
With this UnknownType class:
class UnknownType
{
public void SayHello()
{
Console.WriteLine("Hello world.");
}
}
Usually a desire to do this indicates a misunderstanding. However, there are very occasionally legitimate reasons to do this. It depends on whether or not it's going to be a reference conversion vs an unboxing or user-defined conversion.
If it's a reference conversion, that means the actual value (the reference) will remain entirely unchanged. All the cast does is perform a check and then copy the value. That has no real use - you can perform the check using Type.IsAssignableFrom instead, and just use the implicit cast to object if you want it in a variable of type object.
The main point of casting is to provide the compiler with more information. Now if you only know the type at execution time, that clearly can't help the compiler.
What do you plan to do with o after you've performed the cast? If you can explain that, we can try to explain how to achieve the effect you're after.
If you really want a user-defined conversion or an unboxing conversion to occur, that could be a different matter - but I suspect that's not the case.
EDIT: Having seen your update, your property is just declared to return CustomClass, so all you need is:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
I suspect you still haven't really given us all the information we need. Is that definitely how your property will be defined, with CustomClass being a definite type? Why were you trying to perform the cast dynamically when you know the property type?
EDIT: It sounds like you're just trying to save some typing - to make it easier to cut and paste. Don't. You know the type at compile-time, because you know the type of the property at compile-time (it's specified in the code just a few lines above). Use that type directly. Likewise don't try to get the name of the current method to work out the key to use. Just put the name in directly. Again, you know it at compile-time, so why be dynamic? I'm all for laziness when it makes sense, but in this case it just doesn't.
if (ex is ExampleClass)
{
ExampleClass myObject = (ExampleClass)ex;
}
That would do it but I guess the question is what are you trying to achieve and why? I often find that if something seems really, really difficult then I'm probably doing it wrong.
Now it seems to be impossible, but soon will be available with new feature in .NET 4.0 called "dynamic":
http://www.codeguru.com/vb/vbnet30/article.php/c15645__4/
I'm not entirely sure what you're trying to do, but the impression I'm getting is that you'd like to have a single instance of some object which can "act like" many different types of objects, and you want to have getters which will allow you to view this one object in those various different ways very easily. In that case, I would suggest making a single getter method (not a property), like so:
public T Get<T>()
{
return (T)myObject;
}
Then you would call it like so:
Foo foo = box.Get<Foo>();
Bar bar = box.Get<Bar>();
// etc...
Two things to note: this is definitely not type-safe, since you can pass any type for T, including types for which the cast will fail. You can constrain it a little, like so:
public T Get<T>() where T : SomeBaseType
Which will cause a compile error if you try to use a type which is incompatible with SomeBaseType, but I'm not sure that's totally robust. But hopefully this gets you most of the way there.
Is this what you had in mind?