MalvEarp
MalvEarp

Reputation: 525

In C# How Do You Get Variables From Another Class

I have an API with several classes. Within one class I want to use the variables from the other classes. How do I go about doing this?

Thanks!

public class Rain
{
    public decimal rainValueInCM;
    public decimal rainValueInMM;
   // public Dictionary<decimal, Temperature> Temperature = new Dictionary<decimal, Temperature>();

    public Rain(decimal cm)
    {
        rainValueInCM = cm;
    }

    public  decimal ConvertToCM(decimal mm)
    {   
        rainValueInCM = (mm / 10);
        return rainValueInCM;  
    }

For instance, in another class, I want to use the variable 'rainValueInCM' from this class.

Upvotes: 0

Views: 179

Answers (2)

Agustin Meriles
Agustin Meriles

Reputation: 4854

Simply you have to create an instance of the class Rain and access it values this way:

public class Rain
{
    public decimal rainValueInCM;
    public decimal rainValueInMM;
   // public Dictionary<decimal, Temperature> Temperature = new Dictionary<decimal, Temperature>();

    public Rain(decimal cm)
    {
        rainValueInCM = cm;
    }

    public  decimal ConvertToCM(decimal mm)
    {   
        rainValueInCM = (mm / 10);
        return rainValueInCM;  
    }
}

public class AnotherClass
{
     public void SomeMethod() 
     {
         Rain myRain = new Rain(5); // create the instance
         // use the value
         decimal theValue = myRain.rainValueInCM;
     }
}

Anyway I recommend you to read about C# properties, since there isn't a good practice to expose as public your class value members. Gook luck!

Upvotes: 2

Gabe
Gabe

Reputation: 50493

First you need a getter and setter for the property

public class Rain
{
    public decimal rainValueInCM { get; set; }
    ...
}

Then instantiate an object of type Rain in the other class and get the property

public class MyOtherClass
{
    public void MyMethod() {
         Rain rain = new Rain();
         decimal cm = rain.rainValueInCM;
    }

}

Upvotes: 0

Related Questions