Saturday, October 4, 2008

More C# Discoveries

More C# Discoveries

C# doesn't support #include--unlike C and C++. My first reaction was, "That's disgusting! How do you share data across source files?" The answer is that if you really need to share information across source files, you probably need to define that information as a static or const member of a class (depending on whether it is going to change or not). Then you can access that information in a more elegant and object-oriented manner. For example, in C or C++, you might let everyone know that there are a maximum of fifty customers with an include file that had this line in it:

#define MAX_CUSTOMERS 50

Then everyone that needed access to that information would #include the file containing that statement (and probably dozens of other #defines that weren't needed). This is not only ugly, but slows down compile time. It is surprisingly easy to end up with dozens of include files, each containing hundreds or even thousands of definitions--and eventually, they start to conflict, or worse, nested #includes produce an incomprehensible mess. (I speak from painful experience.)

By comparison, the equivalent in C# would be to add to your class Customers the following line:
public const int maxCustomers = 50;
Now anyone and everyone that needs to know the maximum number of customers just uses Customers.maxCustomers. (Of course, properly designed, there should be no reason for any class other than Customers to need to know this.)

No comments:

Post a Comment