Home > OS >  Assinging a static function from a class to a variable
Assinging a static function from a class to a variable

Time:07-21

I want to be able to assign functions from classes to variables

Ex:

namespace test
{
    class init
    {
        static void Main(string[] args)
        {

            var toSingle = BitConverter.ToSingle;
            
        }
    }

}

    

ERROR The delegate type could not be inferred.

CodePudding user response:

I rather think you might want using static (applied to the top of the file with your other using imports, or just inside your namespace):

using static BitConverter;

This will allow you to simply call ToSingle(...) anywhere in your class.

using static docs

Alternatively, if you really want to assign it to a variable, you could potentially assign it to a delegate (here I'll use Func):

Func<byte[], int, float> toSingle = BitConverter.ToSingle;

Though this won't work if you want to use the overload that takes a ReadOnlySpan<Bye> because it can't be a generic parameter.

  •  Tags:  
  • c#
  • Related