0

I looking for a way to get the name of a class (or struct) which is instantiate under C# 6. Exemple :

public class Test
{
public int myvalue;

public Test(int _myvalue){ myvalue= _myvalue;}
}

void Init()
{
    public Test test= new Test(1);
}

void main()
{
    string nameNewTest = // here what I need, that must return "test", not "Test"
}

I saw lot of topics for find the type like : GetType().Name/nameOf/typeof(Class).Name or some stuff like that but no one for the name of a new variable.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
bobHihi
  • 53
  • 8

1 Answers1

0

You can use

string nameNewTest = nameof(Test);

Without C# 6

string nameNewTest = typeof(Test).Name;

You can look at this post for properties/fields

Community
  • 1
  • 1
A.Pissicat
  • 3,023
  • 4
  • 38
  • 93
  • Yes but without C# 6. – bobHihi Aug 24 '16 at 12:49
  • I edited the answer, you can use `typeof(T).Name` – A.Pissicat Aug 24 '16 at 13:00
  • Take look at the end of my topic, I already try typeof(T).Name but that give me "Test" for my exemple. In your link, that's works only for fields, not for class =/struct – bobHihi Aug 24 '16 at 13:05
  • I don't understand, where did "test" come from ? If you want your class `Test` to lower use `typeof(Test).Name.ToLower()`. If you want the name for variable `public Test test` define in `void Init()` you can't get it in `void main()`because there are separated functions. Where are these both functions declared ? – A.Pissicat Aug 24 '16 at 13:34
  • test is a new class of Test (line 10), and this is an exemple just for explain what I need. – bobHihi Aug 24 '16 at 15:00
  • Did the link solve your problem ? You can do `MemberInfoGetting.GetMemberName(() => test)` – A.Pissicat Aug 24 '16 at 15:07
  • Unfortunately no :/ this works only for field not for instance – bobHihi Aug 24 '16 at 15:20