0

in Object-C, we can use typoef to get type in compile time , for example

Myclass *A = new A;
typeof(A) b = A;

is there something familiar in c#?


edit 1

what i want to to do

//i have a generic function like this, and i can't change it
T getV<T>(string parm)

// i have many members with different type in a class ClassUser
ClassA a;
ClassB b;
Action<int, string, LonglonglonglongClass> c;
...

// when i initialize a ClassUser,i had to write like this 
a = getV<ClassA>("a");
b = getV<ClassB>("b");
c = getV<Action<int, string, LonglonglonglongClass>>("c");
...

//  as you can see , it's annoying, i'd like to write like this
a = getV<typeof(a)>("a");
b = getV<typeof(b)>("b");
c = getV<typeof(c)>("c");
...

edit 2

find a workaround

// wrap the getV
void getV2<T>(string parm ,out T ret)
{
   ret = getV<T>(parm);
}

// write like this
getV2("a" ,out a);
Xt Z
  • 439
  • 4
  • 7
  • 1
    You can always use `var B = A;` – Jawad May 07 '20 at 02:38
  • It would help if you explain what you expect that code to do. Not many people are experts in both Object-C and C#... `typeof` is indeed answer to the question asked in title (and hence duplicate), but there is very good chance you are looking for something else. Some example of C# code you try to compile would be helpful too - not knowing type of an object at compile time is rare in C# (unless you do reflection) so it is possible there some more C#-ish solution to your actual problem. Please [edit] question to clarify so it potentially can be re-opened. – Alexei Levenkov May 07 '20 at 03:02
  • @AlexeiLevenkov ,thanks ,i find a workaround – Xt Z May 07 '20 at 04:32
  • The answer that you've made part of question is standard solution (make return type as one of argument's types) for this as described in https://stackoverflow.com/questions/8511066/why-doesnt-c-sharp-infer-my-generic-types. Please make sure to clarify if you actually still have a question... (and what exactly it is as you seem to have code you are looking for already) – Alexei Levenkov May 07 '20 at 04:40
  • I think you need to clarify what this question is about. It sounds like to me that you're trying to write a factory method that can create new instances of a type that you have an existing instance of. – Enigmativity May 07 '20 at 04:40

1 Answers1

2
Myclass A = new Myclass();

Type objectType = typeof(Myclass);

or

Type objectType = A.GetType();
  • thanks, but i want use type for template ,like ```Myclass A; A = fun("some parm");``` – Xt Z May 07 '20 at 02:46
  • If you want to use a generic type, you can make your class as a generic type like this: public class Myclass and then get the type of T as a property of the class, like this: public Type PurposedType { get { return typeof(T); } } – Farhad Shariatzadeh May 07 '20 at 03:06