views:

77

answers:

3

Sorry guys! i am so into the code! that i forgot to put the compiler errors.

Here is a new version of the code simplified!

And this are the errors:

Error 1 The best overloaded method match for 'IWeird.DataBase.ModifyData(ref IWeird.IDataTable)' has some invalid arguments
Error 2 Argument '1': cannot convert from 'ref IWeird.Periods' to 'ref IWeird.IDataTable'

The problem: I can't pass by reference an interface with a struct in it, what am I doing wrong?

Here is the new example code:

class PeriodsProcessor
    {
        public PeriodsProcessor()
        {
            Periods Data = new Periods();
            DataBase DB = new DataBase();

            Console.WriteLine(Data.Value);
            DB.ModifyData(ref Data);
            Console.WriteLine(Data.Value);

            Console.ReadLine();
        }
    }


    public interface IDataTable
    {
        string Value { get; set; }
    }

    public struct Periods : IDataTable
    {
        public string Value { get; set; }
    }

    public class DataBase
    {
        public void ModifyData(ref IDataTable data) 
        {
            data.Value = "CHANGE";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            PeriodsProcessor PeriodsProcessor = new PeriodsProcessor();
        }
    }
+1  A: 

Structs are value types, not reference types. If you want to pass it by reference, you're going to have to use the ref keyword. Keep in mind though that it's still a value type, and assigning it to another variable is going to create a new struct.

Aaron Daniels
+2  A: 

In your code you are not passing an interface with a struct in it, you are passing a struct that implements an interface. Those are two COMPLETELY different things. As for solving your problem, I don't see a reason to be using a struct at all, so I'd change Periods to be a class.

Payton Byrd
+1  A: 

The problem is in DB.ModifyData<Period>(Data); method call. Your Data field is a struct, structs are passed to any methods by value which means that each time you call a method copy of the struct is created and is passed to the method. So actually your ModifyData method is modifying a copy of the Periods structure that is thrown away just after the method call.

Andrew Bezzub