Mahdi Radi
Mahdi Radi

Reputation: 449

How Pass Referenced DataTable in C#?

I Work on C# Project

I Have 2 Classes Like this:

public class A
{
    public DataTable dtA {get; set;}
}

public class B
{
    DataTable dtB{get;set;}

    public B(DataTable dt)
    {
        dtB = dt;
    }
}

static void Main()
{
    A a = new A();
    B b = new B(a.dtA);
}

I Want that dtB Be Exactly dtA (ref dtA). But with Up Code dtB is New DataTable, And is Not dtA. (i Want When Change dtB , this Change apply on dtA too)

How Solve My Problem?


SOLVED:

if dtA Was null and Pass to dtB, dtB Always Will null.(even When dtA fill with Data) But if dtA was not null and pass to dtB, dtB and dtA Will from One Source.

Upvotes: 1

Views: 9521

Answers (4)

Steve
Steve

Reputation: 216293

Your code works as you intend because DataTable is a reference type. However you need to pay attention because you can easily fall in this situation

void Main()
{
    A a = new A();
    a.dtA = new DataTable("TestTable");
    B b = new B(a.dtA);
    Console.WriteLine(b.TableName); // Same as A.dtA
    Console.WriteLine(a.dtA.TableName);  // Same as internal datatable in B
    a.dtA = new DataTable("SecondTable");
    Console.WriteLine(b.TableName);   // No more the same as A.dtA
    Console.WriteLine(a.dtA.TableName);
}

// Define other methods and classes here
public class A
{
    public DataTable dtA;
}

public class B
{
    DataTable dtB{get;set;}

    public B(DataTable dt)
    {
        dtB = dt;
    }
    public string TableName
    {
        get{ return dtB.TableName;}
        set{ dtB.TableName = value;}
    }
}

As you can see, changing the DataTable in A will leave the DataTable in B still pointing to the old reference and thus the two are no more the same. Check the answer from Tim Schmelter for a better approach.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

If you want to use the same DataTable you should use the same reference of A:

public class A
{
    public DataTable dtA;
}

public class B
{
    public A a;

    public B(A a)
    {
        this.a = a;
    }
}

Now both are using the same table:

static void Main()
{
    A a = new A();
    B b = new B(a);
    Console.Write(a.dtA == b.A.dtA); //true
}

You could also let B inherit from A if that is what you actually want:

public class B: A
{      
}

static void Main()
{
    A a = new A();
    B b = new B();
    Console.Write(a.dtA == b.dtA); //true
}

Upvotes: 0

gzaxx
gzaxx

Reputation: 17590

Both A and B point to the same DataTable, that is because all reference types (as DataTable) are passed by reference so your code should work just fine.

Upvotes: 0

TalentTuner
TalentTuner

Reputation: 17556

try with ref

public B(ref DataTable dt)
{
    dtB = dt;
}

Upvotes: 0

Related Questions