How do I use a class as a template in C#?

192 views Asked by At

I'm not sure if I'm asking that correctly, so bear with me. I'm currently attempting to program a neural network. Below is some sample code.

using System;
namespace Network
{
    class BaseNeuron
        {
            public static void Main (string[] args)
            {
                public int Weight;
                public void sendPulse()
                {
                }
                public void receivePulse()
                {
                }
            }
        }
    }

So basically, I want to be able to create multiple instances of the BaseNeuron class, with each "neuron" tied to other "neurons" to make a Neuron Network. Is there any way to do this without having to reiterate this snippet of code for each neuron?

1

There are 1 answers

10
matan129 On BEST ANSWER

First of all, there are some errors in the code you provided:

class BaseNeuron
{
    public static void Main (string[] args)
    {
        public int Weight;

        public void sendPulse()
        {
        }

        public void receivePulse()
        {
        }
    }
}

It should be:

class BaseNeuron
{            
    //class field
    public int Weight;

    //class method
    public void SendPulse(/*Parameters ...*/)
    {
        //Do stuff
    }

    //class method
    public void ReceivePulse(/*Parameters ...*/)
    {
        //Do stuff
    }            
}

Notice that the Main is gone. Classes normally don't have a Main method, which is usually just the entry point of the application (the first function to get executed when the program runs).

Basically, each class is a template for objects, which means you can create new instances of the class by using the new keyword, like this:

//creating two seperate neurons
neuron1 = new BaseNeuron();
neuron2 = new BaseNeuron();

//Notice that each SendPulse is called on separate objects!
neuron1.SendPulse();
neuron2.SendPulse();

I suggest you read a little bit about class (maybe here) to get a better understanding how this works.

Alright, so now we have our class figured out. You said we wanted to make a network which consists of several neurons, which are instances of the class above. So, what you will probably want to do is:

class Program
{
    public void Main(string[] args)
    {
        //the size of the network
        int size = 5;

        //create array of Neurons
        BaseNeuron[] network = new BaseNeuron[size];

        for(int i = 0; i < network.length; i++)
        {
            //actually create a new nueron (instantiate them)
            network[i] = new BaseNeuron();

            //link up neurons together, etc
        }
    }
}

Of course, the implementation depends of the internal implementation of the BaseNeuron class. You also might need to create a NeuralNetwork class to contain the above code and related functions.