Reputation: 1522
Let's say I have the following C# class:
class MyClass ()
{
public readonly DataTable dt = new DataTable();
...
}
What's the meaning of readonly
for reference types? I just implemented this code and the user is atill able to modify the datatable.
How can I prevent the user from writing or mutating my datatable (or any object in general)? I.e., just read access. Obviously using properties wouldn't help here.
Upvotes: 1
Views: 616
Reputation: 1
readonly means that the Datatable will be a runtime constant as opposed to a compile time constant
Upvotes: 0
Reputation: 2673
you can make a class like this:
class MyClass
{
private DataTable dt = new DataTable();
public MyClass()
{
//initialize your table
}
//this is an indexer property which make you able to index any object of this class
public object this[int row,int column]
{
get
{
return dt.Rows[row][column];
}
}
/*this won't work (you won't need it anyway)
* public object this[int row][int col]*/
//in case you need to access by the column name
public object this[int row,string columnName]
{
get
{
return dt.Rows[row][columnName];
}
}
}
and use it like this example here:
//in the Main method
MyClass e = new MyClass();
Console.WriteLine(e[0, 0]);//I added just one entry in the table
ofcourse if you wrote this statement
e[0,0]=2;
it will produce an error similar to this: Property or indexer MyNameSpace.MyClass.this[int,int] cannot be assigned to --it is read only.
Upvotes: 2
Reputation: 6665
Readonly means that you can not reassign the variable - e.g. later on you can not assign a new DataTable to dt.
As for making the object itself read-only - that entirely depends on the object itself. There is no global convention for making objects immutable.
I didn't see anything specific to achieve this with .NET's DataTable but some options would be to
Upvotes: 4