Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare static classes so that they can be stored within List

Tags:

c#

I am developing a software that takes realtime-data and extracts a number of features from that depending on user input. Each available feature consists of one method that takes an array of doubles and return the wanted feature, such as this one for the MeanAbsoluteValue:

public static class MeanAbsoluteValue{
    public static double Calculate(double[] data){
        return data.Sum(s => Math.Abs(s)) / data.Length;
    }
}

Since each of the features only has the one Calculate method I was thinking of trying to rewrite them so that they can be collected and chosen from that Collection.

I have tried writing an Interface for them to use, but since they are static this was not allowed.

Is there a way of doing this? And if so, could you point me in the right direction?

like image 371
Sander Avatar asked Apr 15 '13 14:04

Sander


People also ask

Where are static classes stored C#?

Singleton objects are stored on the heap while static classes are stored on the stack. How is memory allocated for a static variable? Static variables are stored on the heap, regardless of whether they are declared as a reference type or a value type.

Can I inherit static class in C#?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.

What is a static class?

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.

What does static mean C#?

In C# terms, “static” means “relating to the type itself, rather than an instance of the type”. You access a static member using the type name instead of a reference or a value, e.g. Guid. NewGuid(). In addition to methods and variables, you can also declare a class to be static (since C# 2.0).


1 Answers

You can create an array of delegates constructed from the Calculate methods of these classes, like this:

Func<double[],double>[] array = new Func<double[],double>[] {
    MeanAbsoluteValue.Calculate
,   MeanValue.Calculate
,   Deviation.Calculate
//  ...and so on
};

Here is a demo on ideone.

like image 89
Sergey Kalinichenko Avatar answered Sep 24 '22 19:09

Sergey Kalinichenko