I wish to make a function.
it has parameter like as int or string.
I know typeof keyword. but if typeof keywork use function will be long.
ex)
testFunction(Type type)
{
if(type == typeof(int) Console.WriteLine("int");
}
this.testFunction(typeof(int));
I only want to use int keyword as parameter.
ex)
testFunction( type)
{
if(type == int) Console.WriteLine("int");
}
this.testFunction(int);
How can I do

How can I decleare a function with parameter like int or string keyword?
Solar9
If the function takes a parameter that can be int or string then the best thing you can do is to define 2 functions:
void TestFunc(int a);
void TestFunc(string a);
Now you have 3 choices: using typeof, using a generic function and using overloaded functions. Using the int and string keywords directly without typeof or as generic parameter is not possible.
Another choice and probably the last one that exists is to define something like an enum
enum MyType {
Int,
String
}
and use it as a parameter:
void TestFunc(int a, MyType type);
this.TestFunc(a, MyType.Int);
this.TestFunc(a, MyType.String);
Ben Vanik
Sorry, My english skill is low.
I wish to make a function that it act differently according to a parameter
and the parameter is int C# keyword or string C# keyword, not int type variable or string type variable.
function usage)
int a = 3;
testClass.TestFunc(a, int);
testClass.TestFunc(a, string);
Skapol
Hi PeterPan,
Can you clarify your question
CJW99
You can use method overloading. You define two (or more) methods with the same name. Only you give them different arguments like the sample class below:
public class Test
{
public static void MyFunction( int value )
{
Console.WriteLine( "MyFunction called with an int." );
}
public static void MyFunction( string value )
{
Console.WriteLine( "MyFunction called with an string." );
}
}
Now you can call these methods like this:
int i = 5;
string message = "I love .NET!";
Test.MyFunction( i );
Test.MyFunction( message );
And the output to the console will be:
You can also take a look at this article: C# Method Overloading.
markdrury
If are using .NET 2.0 using a generic function might be an idea:
void testFunction<T>()
{
if (typeof(T) == typeof(int)) Console.WriteLine("int");
}
this.testFunction<int>();