How to declare a function argument that can accept any type in C#

4 Answers

0 votes
using System;
 
class Program
{
    static void AcceptAnyType<T>(T x) {
        if (x is string s) {
            Console.WriteLine(s);
        }
        else {
            Console.WriteLine("Not a string");
        }
    }
 
    static void Main()
    {
        AcceptAnyType("A string");
        AcceptAnyType(809);
    }
}


 
/*
run:
 
A string
Not a string
 
*/

 



answered Jul 31, 2025 by avibootz
edited Jul 31, 2025 by avibootz
0 votes
using System;

public class Program
{
    public static void AcceptAnyType(object x) {
        Console.WriteLine($"The type of the argument is: {x.GetType()}");
    }

    public static void Main()
    {
        AcceptAnyType(384);      // Integer
        AcceptAnyType("ABCD");   // String
        AcceptAnyType(3.14);     // Double
    }
}



/*
run:

The type of the argument is: System.Int32
The type of the argument is: System.String
The type of the argument is: System.Double

*/

 



answered Jul 31, 2025 by avibootz
0 votes
using System;

public class Program
{
    public static void AcceptAnyType(object x) {
        if (x is int) {
            Console.WriteLine("The argument is an integer.");
        }
        else if (x is string) {
            Console.WriteLine("The argument is a string.");
        }
        else if (x is double) {
            Console.WriteLine("The argument is a double.");
        }
        else {
            Console.WriteLine("The argument is of an unknown type.");
        }
    }

    public static void Main()
    {
        AcceptAnyType(384);      // Integer
        AcceptAnyType("ABCD");   // String
        AcceptAnyType(3.14);     // Double
    }
}



/*
run:

The argument is an integer.
The argument is a string.
The argument is a double.

*/

 



answered Jul 31, 2025 by avibootz
0 votes
using System;

public class Program
{
    public static void AcceptAnyType<T>(T x) {
        Console.WriteLine($"The type of the argument is: {typeof(T)}");
    }

    public static void Main()
    {
        AcceptAnyType(384);      // Integer
        AcceptAnyType("ABCD");   // String
        AcceptAnyType(3.14);     // Double
    }
}



/*
run:

The type of the argument is: System.Int32
The type of the argument is: System.String
The type of the argument is: System.Double

*/

 



answered Jul 31, 2025 by avibootz
...