I have a method with the following signature:
string GetTableCellValue(DataTable table, string columnName, int rowIndex){}
As you might guess, this method returns the value of the cell located at the specified column of the specified row of the specifies table in string format. It turns out that I need this methods almost in all the webpages. Here's my quetion(s):
The last 2 choices seem to be better idea. But I don't know which one to choose eventually.
Solution 2. You use static methods when the method does not need to access any non-static class elements such as properties, events, or methods in order to do it's job.
Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.
You cannot call static methods using an object of the non-static class. The static methods can only call other static methods and access static members.
You probably want to create a static method for this. Specifically, an extension method:
public static class Extensions
{
public static string GetTableCellValue(this DataTable table,
string columnName, int rowIndex)
{
// ...
}
}
Now, you can call it like an instance method on your DataTable
objects:
DataTable dataTable = ...;
var value = dataTable.GetTableCellValue("column", row);
I would go for the second option as I wont require the instance of the class e.g Utilities_Class. GetTableCellValue has nothing to do with its data members or methods to making it static is quite reasonable. Make it extension method to call it just like it exists in DataTable class.
public static class DataExtensions
{
public static string GetTableCellValue(this DataTable table, string columnName, int rowIndex)
{
// implementation
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With