Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,941 questions

51,879 answers

573 users

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
...