0

Consider a struct type defined as follows:

public struct Device
{
    public string Name {get; set;}
    public string Data {get; set;}

    public void UploadData(DataSource source)
    {
        source.data += Data;
    }
}

Now, I would like to change the Device to a class type and use it to describe different types of devices:

public class Device
{
    public string Name {get; set;}
    public string Data {get; set;}

    public virtual void UploadData(DataSource source)
    {
        source.data += Data;
    }
}

I'm aware that one should be cautious in making this step because the parameters are passed by reference in the second case. But somehow I can't figure out a use case where this change will have negative consequences for uploading data to the data source.

mjwills
  • 23,389
  • 6
  • 40
  • 63
Danila Kireev
  • 84
  • 1
  • 1
  • 11
  • 1
    "the parameters are passed by reference in the second case" - no they're not. The reference is passed by value. It's really important to understand the difference. See https://jonskeet.uk/csharp/parameters.html – Jon Skeet Jul 27 '20 at 09:48
  • 1
    `var a = new Device() { Name = "a"}; var b= a; b.Name = "b";` Compare and contrast (i.e. run the code, look at `b` and `a` when class, then as struct). – mjwills Jul 27 '20 at 09:50
  • @JonSkeet, oh.. now I see the difference. Great article btw! Was a pleasure to read. – Danila Kireev Jul 27 '20 at 10:11
  • @mjwills, makes sense:) if you like, you can post this comment as an answer and i"ll accept it. – Danila Kireev Jul 27 '20 at 10:19

0 Answers0