TypeScript: Type of the current class as a type variable
There is not a way to do this yet in TypeScript. See issue https://github.com/Microsoft/TypeScript/issues/285 for voting/discussion.
Casting a variable using a Type variable
Here is an example of a cast and a convert:
using System;
public T CastObject<T>(object input) {
return (T) input;
}
public T ConvertObject<T>(object input) {
return (T) Convert.ChangeType(input, typeof(T));
}
Edit:
Some people in the comments say that this answer doesn't answer the question. But the line (T) Convert.ChangeType(input, typeof(T))
provides the solution. The Convert.ChangeType
method tries to convert any Object to the Type provided as the second argument.
For example:
Type intType = typeof(Int32);
object value1 = 1000.1;
// Variable value2 is now an int with a value of 1000, the compiler
// knows the exact type, it is safe to use and you will have autocomplete
int value2 = Convert.ChangeType(value1, intType);
// Variable value3 is now an int with a value of 1000, the compiler
// doesn't know the exact type so it will allow you to call any
// property or method on it, but will crash if it doesn't exist
dynamic value3 = Convert.ChangeType(value1, intType);
I've written the answer with generics, because I think it is a very likely sign of code smell when you want to cast a something
to a something else
without handling an actual type. With proper interfaces that shouldn't be necessary 99.9% of the times. There are perhaps a few edge cases when it comes to reflection that it might make sense, but I would recommend to avoid those cases.
Edit 2:
Few extra tips:
- Try to keep your code as type-safe as possible. If the compiler doesn't know the type, then it can't check if your code is correct and things like autocomplete won't work. Simply said: if you can't predict the type(s) at compile time, then how would the compiler be able to?
- If the classes that you are working with implement a common interface, you can cast the value to that interface. Otherwise consider creating your own interface and have the classes implement that interface.
- If you are working with external libraries that you are dynamically importing, then also check for a common interface. Otherwise consider creating small wrapper classes that implement the interface.
- If you want to make calls on the object, but don't care about the type, then store the value in an
object
ordynamic
variable. - Generics can be a great way to create reusable code that applies to a lot of different types, without having to know the exact types involved.
- If you are stuck then consider a different approach or code refactor. Does your code really have to be that dynamic? Does it have to account for any type there is?
How to use the Type class as type in variable declaration
No there isn't. When you create a generic List
, you must specify a data type. A Type
object is not a data type. It's an object that contains information about a data type. Basically, when you create a List(Of T)
you can only fix T
to be something that you could have passed to GetType
in the first place. Both require data types.
You can't put data types in a list because they are not objects. What you could do is write a generic method that does what you want for one type, e.g.
Private Sub DoStuff(Of T)()
Dim newList As New List(Of T)
'Do stuff here.
End Sub
and then call that method and specify different generic types, e.g.
DoStuff(Of SomeType)()
DoStuff(Of SomeOtherType)()
'Etc.
You have to make individual calls though, because you need to specify the generic type.
Declaration variable with type in variable of type 'Type'
First problem: I need declare new variable with type stored in MyType.
You can't do this, basically.
Variable types need to be known at compile-time. You can't declare a variable using a type which is only known at execution time. You can get some of the way there using generics:
public class Foo<T>
{
private T value;
}
You can even add a constraint to require that T
has a parameterless constructor which you can then call:
public class Foo<T> : new()
{
private T value = new T();
}
... and you could create a Foo<T>
when you only know the type of T
at execution time using reflection:
Type genericDefinition = typeof(Foo<>);
Type constructed = genericDefinition.MakeGenericType(A.MyType);
object instance = Activator.CreateInstance(constructed);
... but it will get messy pretty quickly. You haven't told us anything about what you're actually trying to achieve, so it's hard to suggest an alternative - but if you can possibly redesign to avoid this, I would.
Second problem: I need a function that indicates whether reducible to each other variables of the 'Type'
It's possible that you're looking for Type.IsAssignableFrom
, but it's not clear...
Get the Type of a Variable Being Assigned to From Within a Method
Is there a way to get the type of the variable being assigned to from within the method?
No. There is no way for a method to retrieve any information about the variable that its result will be assigned to.
However, you could use generics to tell the method the type of object you want it to return:
double dbl = AssignValue<double>("Hello");
public T AssignValue<T>(object valueToAssign)
{
Type type = typeof(T);
switch(type.Name)
{
//...
}
}
cast with a Type variable
It is not possible to use a Type
value to determine the type of an expression. (Generics type parameters are different than values as they are codified into the type-system.)
The value of the variable is from the run-time code execution, while the expression type is a compile-time construct. Needless to say, the compilation occurs before the code ever runs so using a variable for a cast is impossible.
Reflection (albiet unwieldy) or dynamic
(which is basically easier-to-use-reflection) allow invoking arbitrary methods or accessing properties/fields against a generic object-typed expression - this is occasionally refered to as "late binding". However, the type of the expression upon which operations is invoked is still object.
Interfaces can be used to unify disparate class implementations for proper static typing. The newly created object can then cast to the applicable interface(s) are required. Just like with other expressions, the type is a compile-time construct (and as such the interface must be directly specified), but the code is now free from a particular class.
If creating a system such that these "dynamic classes" are to be used directly in statically typed (C#) code, and the interfaces can be guaranteed or are constrained to a small set, then using interfaces is likely the cleanest approach: e.g. var myAction = (IMyAction)obj
. Otherwise, fall back to dynamic access - direct or behind a facade.
How to reference a generic return type with multiple bounds
While the type parameters of a generic method can be restricted by bounds, such as extends Foo & Bar
, they are ultimately decided by the caller. When you call getFooBar()
, the call site already knows what T
is being resolved to. Often, these type parameters will be inferred by the compiler, which is why you don't usually need to specify them, like this:
FooBar.<FooAndBar>getFooBar();
But even when T
is inferred to be FooAndBar
, that's really whats happening behind the scenes.
So, to answer your question, such a syntax like this:
Foo&Bar bothFooAndBar = FooBar.getFooBar();
Would never be useful in practice. The reason is that the caller must already know what T
is. Either T
is some concrete type:
FooAndBar bothFooAndBar = FooBar.<FooAndBar>getFooBar(); // T is FooAndBar
Or, T
is an unresolved type parameter, and we're in its scope:
<U extends Foo & Bar> void someGenericMethod() {
U bothFooAndBar = FooBar.<U>getFooBar(); // T is U
}
Another example of that:
class SomeGenericClass<V extends Foo & Bar> {
void someMethod() {
V bothFooAndBar = FooBar.<V>getFooBar(); // T is V
}
}
Technically, that wraps up the answer. But I'd also like to point out that your example method getFooBar
is inherently unsafe. Remember that the caller decides what T
gets to be, not the method. Since getFooBar
doesn't take any parameters related to T
, and because of type erasure, its only options would be to return null
or to "lie" by making an unchecked cast, risking heap pollution. A typical workaround would be for getFooBar
to take a Class<T>
argument, or else a FooFactory<T>
for example.
Update
It turns out I was wrong when I asserted that the caller of getFooBar
must always know what T
is. As @MiserableVariable points out, there are some situations where the type argument of a generic method is inferred to be a wildcard capture, rather than a concrete type or type variable. See his answer for a great example of a getFooBar
implementation that uses a proxy to drive home his point that T
is unknown.
As we discussed in the comments, an example using getFooBar
created confusion because it takes no arguments to infer T
from. Certain compilers throw an error on a contextless call to getFooBar()
while others are fine with it. I thought that the inconsistent compile errors - along with the fact that calling FooBar.<?>getFooBar()
is illegal - validated my point, but these turned out to be red herrings.
Based on @MiserableVariable's answer, I put together an new example that uses a generic method with an argument, to remove the confusion. Assume we have interfaces Foo
and Bar
and an implementation FooBarImpl
:
interface Foo { }
interface Bar { }
static class FooBarImpl implements Foo, Bar { }
We also have a simple container class that wraps an instance of some type implementing Foo
and Bar
. It declares a silly static method unwrap
that takes a FooBarContainer
and returns its referent:
static class FooBarContainer<T extends Foo & Bar> {
private final T fooBar;
public FooBarContainer(T fooBar) {
this.fooBar = fooBar;
}
public T get() {
return fooBar;
}
static <T extends Foo & Bar> T unwrap(FooBarContainer<T> fooBarContainer) {
return fooBarContainer.get();
}
}
Now let's say we have a wildcard parameterized type of FooBarContainer
:
FooBarContainer<?> unknownFooBarContainer = ...;
We're allowed to pass unknownFooBarContainer
into unwrap
. This shows my earlier assertion was wrong, because the call site doesn't know what T
is - only that it is some type within the bounds extends Foo & Bar
.
FooBarContainer.unwrap(unknownFooBarContainer); // T is a wildcard capture, ?
As I noted, calling unwrap
with a wildcard is illegal:
FooBarContainer.<?>unwrap(unknownFooBarContainer); // compiler error
I can only guess that this is because wildcard captures can never match each other - the ?
argument provided at the call site is ambiguous, with no way of saying that it should specifically match the wildcard in the type of unknownFooBarContainer
.
So, here's the use case for the syntax the OP is asking about. Calling unwrap
on unknownFooBarContainer
returns a reference of type ? extends Foo & Bar
. We can assign that reference to Foo
or Bar
, but not both:
Foo foo = FooBarContainer.unwrap(unknownFooBarContainer);
Bar bar = FooBarContainer.unwrap(unknownFooBarContainer);
If for some reason unwrap
were expensive and we only wanted to call it once, we would be forced to cast:
Foo foo = FooBarContainer.unwrap(unknownFooBarContainer);
Bar bar = (Bar)foo;
So this is where the hypothetical syntax would come in handy:
Foo&Bar fooBar = FooBarContainer.unwrap(unknownFooBarContainer);
This is just one fairly obscure use case. There would be pretty far-ranging implications for allowing such a syntax, both good and bad. It would open up room for abuse where it wasn't needed, and it's completely understandable why the language designers didn't implement such a thing. But I still think it's interesting to think about.
Note - Since JDK 10 there is the var
reserved type name, which makes this possible:
var fooBar = FooBarContainer.unwrap(unknownFooBarContainer);
The variable fooBar
is inferred to have a type that implements both Foo
and Bar
and that cannot be denoted explicitly in source code.
A note about heap pollution
(Mostly for @MiserableVariable) Here's a walkthrough of how an unsafe method like getFooBar
causes heap pollution, and its implications. Given the following interface and implementations:
interface Foo { }
static class Foo1 implements Foo {
public void foo1Method() { }
}
static class Foo2 implements Foo { }
Let's implement an unsafe method getFoo
, similar to getFooBar
but simplified for this example:
@SuppressWarnings("unchecked")
static <T extends Foo> T getFoo() {
//unchecked cast - ClassCastException is not thrown here if T is wrong
return (T)new Foo2();
}
public static void main(String[] args) {
Foo1 foo1 = getFoo(); //ClassCastException is thrown here
}
Here, when the new Foo2
is cast to T
, it is "unchecked", meaning because of type erasure the runtime doesn't know it should fail, even though it should in this case since T
was Foo1
. Instead, the heap is "polluted", meaning references are pointing to objects they shouldn't have been allowed to.
The failure happens after the method returns, when the Foo2
instance tries to get assigned to the foo1
reference, which has the reifiable type Foo1
.
You're probably thinking, "Okay so it blew up at the call site instead of the method, big deal." But it can easily get more complicated when more generics are involved. For example:
static <T extends Foo> List<T> getFooList(int size) {
List<T> fooList = new ArrayList<T>(size);
for (int i = 0; i < size; i++) {
T foo = getFoo();
fooList.add(foo);
}
return fooList;
}
public static void main(String[] args) {
List<Foo1> foo1List = getFooList(5);
// a bunch of things happen
//sometime later maybe, depending on state
foo1List.get(0).foo1Method(); //ClassCastException is thrown here
}
Now it doesn't blow up at the call site. It blows up sometime later when the contents of foo1List
get used. This is how heap pollution gets harder to debug, because the exception stacktrace doesn't point you to the actual problem.
It gets even more complicated when the caller is in generic scope itself. Imagine instead of getting a List<Foo1>
we're getting a List<T>
, putting it in a Map<K, List<T>>
and returning it to yet another method. You get the idea I hope.
How to reference type of self in Typescript interface (for a IClonable interface)
Very simply set return type as (polymorphic) this
:
interface ICloneable {
clone(): this;
}
A polymorphic
this
type represents a type that is the subtype of the
containing class or interface. This is called F-bounded polymorphism.
Important Note
There seems to be an [issue][5] with actually using an interface defined like the one above, in a class. The problem is that attempting to override the method in a new class does not work. My suggestion atm would be to hold off on using this syntax or not to use it in an interface and prefer to use a class so that you can provide a basic implementation.
It seems that it was introduced mostly to be able to do method chaining properly.
What the OP had initially seems to be the current best way to accomplish this:
interface ICloneable<T> {
clone(): T;
}
class A implements ICloneable<A> {
constructor(readonly a: number){}
clone() {
return new A(this.a);
}
}
or even
interface ICloneable {
clone(): ICloneable;
}
as another answer pointed out.
How to reference an existing class object with no defined variable?
* Edited based on OP's clarification *
If you have a large number of objects you want to refer to without binding them to variables, dict
is the way to go.
You can use @Berci's solution. But note that with that solution, if you already have a room named foo
, you can't overwrite it by simply calling Room('foo')
again -- doing that will just return the original foo
room. To overwrite an existing room you must first do del Room.roomDict['foo']
, and then call Room('foo')
. This may be something you want, but maybe not.
The implementation below is less fanciful and doesn't require __new__
(in fact, Berci's solution doesn't need __new__
either and can be all done in __init__
):
class Room:
registry = {}
def __init__(self, name):
self.registry[name] = self
# the rest of your __init__ code
If you want rooms to be non-overwritable, as they are in Berci's solution, just add two lines:
class Room:
registry = {}
def __init__(self, name):
if name in self.registry:
raise ValueError('room named "{}" already exists'.format(name))
self.registry[name] = self
It's not necessary to nest registry
inside Room
. You can make it an external dict if you want. The advantage of having the registry as a class attribute is that your Room
object can access it as self.registry
without knowing its global name. The (slight) disadvantage is that you need to type Room.registry
or someroom.registry
instead of just, say, registry
, every time you access it.
Related Topics
Why Is Spawning Threads in Java Ee Container Discouraged
Is There a Goto Statement in Java
How to Extract Numbers from a String and Get an Array of Ints
Where Does the @Transactional Annotation Belong
Java 8 Localdate Jackson Format
How Many Significant Digits Do Floats and Doubles Have in Java
"Loop:" in Java Code. What Is This, and Why Does It Compile
Generationtype.Auto VS Generationtype.Identity in Hibernate
How to Get the Cellrow When There Is an Itemevent in the Jcombobox Within the Cell
How Many Threads Can a Java Vm Support
Unicode Equivalents For \W and \B in Java Regular Expressions
What Is the Ellipsis (...) For in This Method Signature
Java: Prefix/Postfix of Increment/Decrement Operators
Try/Catch With Inputmismatchexception Creates Infinite Loop