How can I declare a method then define it later? - c#

In C# is there a way to declare the class then define it later? I really like in C++ where I can list all the methods at the top like a TOC then define everything later.
Can that be done is C#?
I have used the idea of defining a method that just runs a similarly named method in it then the similar method is at the bottom. but I am thinking there is a better way and googling returns a bunch of basic code on creating classes with no answer.
so here is what I do...
...
public void methodA(){methodAcontent()};
public void methodB()...etc...
...further down...
private void methodAcontent(){
...All the code..
}
is there a better way?

this like Interface http://msdn.microsoft.com/en-us/library/87d83y5b.aspx

Or this an Abstract class with abstract methods.

There's not a good way to do this in the C# language, but the Visual Studio IDE can collapse a file to its definitions which you can then expand individually (see this). This along with code regions helps me organize longer files.

Why would you need that?
C# is using multipass compilation, so it doesn't matter where the function is defined and when used. You can have function defined at end of the class and use it in the beginning and it will still compile fine.
Also IDE helps you with that. You have ability to collapse bodies of all methods, there is list of all methods in one combobox and InteliSense is extremly helpful in finding correct methods.
And using practices from C++ in C# is really bad idea, because both are quite different in how they solve the problems.

If you're doing this as a means to "document" the public interface to a class that's properly encapsulating a concept or object in your problem domain, then use an interface.
If you're doing it as a means to get an "overview" the structure of a class, then Visual Studio has several ways to give you this. You can collapse the code to just its definitions (Ctrl+M, O), or look at the Class View (Ctrl+W, C).

Related

Constructor with no definition

I'm new to .Net and I just saw this code that doesn't make sense to me (slightly abridged):
namespace test
{
public class sub : super
{
public sub(string text);
}
}
As you can see, there is a constructor that takes an argument, but does not implement a definition. How does that work? My guess is that it somehow relates to the super class, but I dont understand how, and I havent been able to find anything on Google.
Edit: Im running this in VS2010, and I just noticed that the tab has [from metadata] in the title. Perhaps this is why?
That's not code.
That's text that looks somewhat like code based on the metadata in the assembly. You'll see this when the IDE doesn't have access to the source code in question (For example, you press F12 on a method in a referenced assembly.) It provides the method signatures, properties, fields, etc from the types, without providing any of the actual implementation.
As written, the code you posted wouldn't even compile in C#.
If from the metadata, it's not going to show you the implementation of the methods.
It looks like code but it is text based on the metadata in the assembly. It means that the IDE is unable to access the source code in question.

How to extract a method to a separate class

I have a method which accesses many fields, so it’s hard coded into its class. I would like to make it reusable by other classes.
Is there any way of getting a list of all fields and methods (within the same class) that a method accesses?
I’m using VS2010.
Sure, take that method out of the class and put it into an empty class and try to compile. Compiler will complain about a list of fields that this method wants to access but could not find.
The Reflection namespace can do just about anything you'd need in this regard. Specifically, I think you'll want to check out System.Reflection.PropertyInfo and System.Reflection.MemberInfo.

Inherit a class but it's usually created with a static method?

I've got a class that I would like to inherit. i.e. ExpenseForm should inherit from Spreadsheet. Spreadsheet is provided by a third party: I can't change it.
But parent class instances are usually generated with a static method:
Spreadsheet myExpenses = Spreadsheet.Open(filename);
(And Spreadsheet implements iDisposable, so the above statement is actually at the top of a using section, but I don't think that really affects this.)
I'd like to have
ExpenseForm myExpenses = ExpenseForm.Open(filename);
This fails, of course, since ExpenseForm.Open (inherited from Spreadsheet) returns a Spreadsheet object.
What's the best way to solve this? Maybe extension methods? (I have no experience with those.)
I've gone a different direction; ExpenseForm now has an instance of Spreadsheet. (This feels a little messier, since I have to keep track of my disposable object to clean up when I'm done.) But it seems like I'm missing a way to solve the original inheritance problem.
Well you can create your own ExpenseForm.Open method easily enough:
public static new ExpenseForm Open(string file)
{
// Do whatever you need
}
That's assuming you can create a subclass, i.e. that there are appropriate constructors you can chain to. You say that you would normally use Spreadsheet.Open, but are there protected or public constructors available?
Personally I'd favour the composition route anyway - do you actually want other code to treat an ExpenseForm as if it were any other kind of Spreadsheet? I'm generally more of a fan of composition than inheritance - it makes code easier to reason about, in my experience.
If Spreadsheet objects can only be created by means of a static function, then inheritance is not an option. Just provide your own Open static function within ExpenseForm that returns an object of that kind.

Is using static classes whenever i can good practice?

Let me be more precise. In my winforms project im creating classes to manage/create every part of the program. I did it to have more control over my code. E.g. I have a class that manages my DataGridView control. I named it gridManager and in it i set all properties, colors and so on and also i have methods to change those settings (e.g. changeBackgroundColor() etc).
I also have this type of class for each Panel in splitContainer. In those classes i initialize every Control that is a child of panel i add them to that panel set all properties and so on.
I wrote it all to give you better view at the purpose of those classes.
Now my question is: is it good practice to make this classes static? With all controls and methods inside being static?
At first i had them non-static but when i wanted to call methods for (e.g.) changing color from options Form i had to either pass MainForm as a parameter or do it like this:
(Application.OpenForm[0] as MainForm).gridManager.changeColor();
Static version of it makes it a lot easier. But it makes me wonder if its a good thing to do.
Uh a lot of explaining i hope my not perfect English wont make it even more difficult to understand. :)
Global mutable state is usually a bad idea.
Static methods/classes are good for simple sideeffect free functions. Math and Enumerable are good examples.
You on the other hand want controls inside static fields. These are mutable state and thus should be avoided. For example if you tomorrow want to have two instances of your form, you need two instances of your manager class. But it's static and you now need to rewrite all the code using it.
Like anything, static classes have tradeoffs. The two "negative" ones that come to mind are
You can't inherit from static classes
You can't (easily) mock static classes for testing
But it sounds like in your cases you wouldn't be doing any inheritance of these classes anyway, so perhaps in this case it would be okay.
Edit This is assuming you're doing something like a control factory.
For example:
var grid = GridManager.CreateGrid(options);
If you're doing something like
var data = GridManager.GetDataFromGrid(myGrid)
I'd probably reconsider.
Static classes have their place, but this probably is not one of them unless it is a quick and dirty application. If you want to have automated tests around your code, it can be nearly impossible if the code under test uses static classes for preferences.
It might be better to use the singleton pattern. This way you can replace the implementation during the automated test.
You better do it with normal classes that is linked to that grid object. If you need another grid object you may need to instantiate another instance. Controllers are not the best candidate for static classes.
Its neither good nor bad practice, its just a common pattern for certain tasks.
Generally speaking you would use static methods for functionality that is related to a class type but does not rely upon any instance data to work, a classic use would be something like a factory type method that returns an initialized instance of the class its attached to.
public SomeClass = SomeClass.CreateWithSomeInit(parms);
Static classes certainly have their place, but I think that using them whenever you can is a bad advice.
The whole concept of OOP is built around instances and so you should use non-static classes most of the time. The reason? Primarily flexibility. You can have two instances that do the same thing is a slightly different way based on their internal state. You can have more implementations of the same concept and you can easily switch them. You can use things like Inversion of Control containers. And so on.

C# - Creating a code file with common definitions/constants/enums etc?

In C++ I'd often create a code file containing constants, enums, #define-s, macros etc.
What's the best practice for that in C#? Do I create a static class and fill it with that data? or is there some other way ?
You don't need a static class for enums - they can be top-level (meaning: namespace level). Yes, you need a class for constants (and a static class would suffice), but I would tend to have multiple classes - one per intent. There is no need to cram them all together.
In C#, any #define only apply to that file, so there is not much point having a class for them (put them in the project / build-script instead). And macros don't exist.
If you have some items you want to define Globally, like a set of strings, I would use a static class with Static properties. I would do that if you are going to use it in more than 1 place.
If you are going to use a defined string for example in just once place, then I would put it in the class that is referencing it.
It is very important to use properties and not expose members. I have found with C++ developers I have worked with when they move to C# they expose members because they have no need for "the special logic of a property". While that may be true when you initially are writing the code. If you expose it as a member and need to do special logic then you have to refactor in a major way. While if you begin as a property then you can add the logic with no refactoring.
For Enums I tpyically define an Enum.cs file inside the folder that represents the namespace. Rather than define them inside a static class.
Macros:
Macros don't exist in C#.
#Defines:
defines are very restricted and only really used for conditional compilation. You should define them by using the project properties (or in your msbuild script) instead.
Enums:
Enums should each go in their own separate file. They don't need to be within a class, they just go directly in the name space.
Constants:
Personally I try to keep constants to a minimum, and private within a class where possible.
If you do have to make them public and globally available, use a static class (or a normal class if they relate directly to one nicely). Try to group them into classes by their use.
If you are talking about string constants, you could consider using a resource file instead if they are localizable strings.
Usually there is a class or struct for which your enum etc. particular applies. I put it in that file, under the class. It's easy to get to the definition from anywhere it's used in code. When possible, I try to put all similar entities for a namespace (or other logical grouping) in the same place.
I'd already object to that practice in C++.
Define that stuff where you need it and not in a single "dump" file. This kind of file tends to accumulate huge amounts of unused stuff over time. And it's hard to clean up because who knows, which parts of your code is using it...

Categories

Resources