Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Common methods for different objects
Message
From
21/05/2009 13:04:25
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 3.0
OS:
Windows XP
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01400964
Message ID:
01401361
Views:
37
>>(2) create a class that implements those methods
>>Add it to the grids that will use it
>>Call the methods of that class
>>
>>(3) Extension methods
>>- either for all grids
>>- or for a subclass of the grid's class
>>
>>
>>There will be other ways
>>
>>
>Could you please explain 2 and 3 with details (samples)?
>
>Thanks in advance.


(3) Extension methods
Message#1360553 - bottom is based on an interface
message#1370231

(2)
The idea is simple. There are two different classes, test1 and test2, that need some methods that do the same
In both test1 and test2, I add an object (Helper) which has a method sum()

Sum() can be called both from within test1 and test2

It's also possible to instantiate Helper each time you need it, then it won't be a member of neither test1 nor test2
	public class test1
	{
		SumHelper Helper = new SumHelper();

		public void test()
		{
			List<int> theList = new List<int> { 1, 2, 3, 4 };

			int result = Helper.Sum(theList);
		}
	}

	public class test2
	{
		SumHelper Helper = new SumHelper();

		public void test()
		{
			List<int> theList = new List<int> { 7,8,9,10 };

			int result = Helper.Sum(theList);
		}
	}

	public class SumHelper
	{
		public int Sum(List<int> theList)
		{
			int total = 0;
			foreach (int item in theList)
			{
				total += item;
			}
			return total;
		}
	}
An alternative (suggested by Tim) is to have a helper class with a static method
	public class test1
	{

		public void test()
		{
			List<int> theList = new List<int> { 1, 2, 3, 4 };

			int result = SumHelper.Sum(theList);
		}
	}

	public class test2
	{

		public void test()
		{
			List<int> theList = new List<int> { 7,8,9,10 };

			int result = SumHelper.Sum(theList);
		}
	}

	public class SumHelper // the class should be static if all of its methods are static
	{
		public static int Sum(List<int> theList)
		{
			int total = 0;
			foreach (int item in theList)
			{
				total += item;
			}
			return total;
		}
	}
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform