Tuesday, March 17, 2015

Get type name of a variable in C++/C#

#include<typeinfo>
#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

void main()
{
int nIntNum = 10;
float fFloatNum = 20.5;

std::string strStringVar = "Iam String";

double dDouble = 2.001;

cout <<"Iam :"<< typeid(nIntNum).name()<<endl;
cout <<"Iam :"<< typeid(fFloatNum).name() << endl;
cout <<"Iam :"<< typeid(strStringVar).name() << endl;
cout << "Iam :" << typeid(dDouble).name() << endl;

_getch();

}

Output :

Iam : int
Iam : float
Iam : class std::basic_string
Iam : double


using System;
namespace MyNamespace
{
class MyProgram
{
 static void Main(string[] args)
 {
   var strStringVar = "Bugs Bunny";
   var nIntNum = 25;
   var fFloatNum = 25.3;
   Type IntType = nIntNum.GetType();
   Type strType = strStringVar.GetType();
   Type FloatType = fFloatNum.GetType();
   Console.WriteLine("Iam " + IntType.ToString());
   Console.WriteLine("Iam " + strType.ToString());
   Console.WriteLine("Iam " + FloatType.ToString());
   Console.ReadLine();
 }
 }
}

The output:
Iam System.Int32
Iam System.String
Iam System.Single

No comments:

Post a Comment