Reputation: 57
I am fairly new to C# so be gentle.
My end goal is to have a few different types of classes for inheritance (example below: Level). These inherited classes do two things, have .Value property with different setters depending on the class, and a .Action method, unique for every instance so it is an override.
Question: how do i set the .Value property from a method on the class. This is the line of code (line 27) that does not work from the example below. And I don't understand why.
Potentiometer.Value = Convert.ToDouble(data);
// Code taken from https://dotnetfiddle.net/YNJpjf
using System;
namespace Main {
class Program
{
static Device device = new Device();
static void Main(string[] args)
{
device.HandleDataUpdate("50");
}
}
public class Device
{
public class Potentiometer : Level
{
public override void Action()
{
Console.WriteLine("value is at: {0}", this.Value);
}
}
public void HandleDataUpdate(String data)
{
Potentiometer.Value = Convert.ToDouble(data);
}
}
public class Level
{
private Double thisValue;
public Double Value
{
get => thisValue;
set
{
if (thisValue != value)
{
thisValue = value;
Action();
}
}
}
public virtual void Action()
{
}
}
}
Upvotes: 1
Views: 710
Reputation:
You're trying to set value of class field, which is impossible, not of object's field. You have to make instance of Potentiometer
inside the Device
, if you want to do this , you could make method or change code logic.
Upvotes: 0
Reputation: 726579
Give Level
a protected abstract method OnSetValue
, forcing each subclass to override it. Now the setter of Value
can call OnSetValue
before the value is set:
public class Level {
private double val;
public double Value {
get {
return val;
}
set {
OnSetValue(value);
val = value;
}
}
protected abstract void OnSetValue(double val);
...
}
public class Potentiometer : Level {
protected void OnSetValue(double val) {
...
}
}
Upvotes: 1
Reputation: 1979
You need to create an instance of Potentiometer.
https://dotnetfiddle.net/8JQDyO
Upvotes: 0