|
public class Something
{
public Something()
{
Backcolor = clgreen;
}
public Something(string name)
: this()
{
Label.text = name
}
}
A positive attitude may not solve every problem, but it will annoy enough people to be worth the effort.
modified 28-May-14 17:14pm.
|
|
|
|
|
wow, I didn't expect it to be that simple.
In the article the first constructor is calling the second constructor and the second constructor is calling the third constructor.
namespace Dummy
{
public class Something
{
private string myName;
private int myIndex;
public Something()
{
myName = "default";
myIndex = -1;
DoStuff();
}
public Something(string name)
{
myName = name;
myIndex= -1;
DoStuff();
}
public Something(string name, index)
{
myName = name;
myIndex= index;
DoStuff();
}
private void DoStuff()
{
}
}
This is the other way around.
Instead of doing most of the initializing in the first constructor. In the article all initialisation is done in the third (last) constructor.
Which one is the better way to develop.
|
|
|
|
|
Well, you can seriously simplify your logic here:
namespace Dummy
{
public class Something
{
private string myName;
private int myIndex;
public Something() : this("default", -1)
{
}
public Something(string name): this(name, -1)
{
}
public Something(string name, index)
{
myName = name;
myIndex= index;
DoStuff();
}
private void DoStuff()
{
}
} As the three constructors are doing the same thing, with the first two providing default values, simply adding the logic into the final constructor makes things simpler. This example is no longer violating the DRY principle (Don't Repeat Yourself).
|
|
|
|
|
sneezesnoeze wrote: I have no clue why a default constructor would call the more complex constructor. Because someone created a named Something, or because another constructor points to it.
using System;
using System.Windows.Forms;
using System.Drawing;
namespace ConsoleApplication1084
{
class Program
{
public class something
{
Color _backColor;
public something()
{
Console.WriteLine("Fiiiiiiiiiiiiirst!");
}
public something(string name): this (name, Color.Green)
{
Console.WriteLine(string.Format("Name = {0}", name));
}
public something(string name, Color backColor): this()
{
_backColor = Color.Green;
Console.WriteLine(string.Format("Name = {0}", name));
Console.WriteLine(string.Format("Color = {0}", _backColor));
}
}
static void Main()
{
new something("Hello world");
Console.ReadLine();
}
}
}
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
sneezesnoeze wrote: I have no clue why a default constructor would call the more complex constructor.
Surprisingly, this is common and reasonable.
This is to accomplish providing default values for the various parameters of the complex constructor.
See section "10.11.6 Optional instance constructor parameters" of the : C# Language Specification[^]
Starting with C# 4.0 optional arguments (see C# Language Features, From C# 2.0 to 4.0[^]) provides this capability if the default values are constant value expressions (or new S() or default(S) where S is a value type):
See section "10.6.1 Method parameters" of the C# Language Specification (linked above).
A positive attitude may not solve every problem, but it will annoy enough people to be worth the effort.
|
|
|
|
|
There's two ways to write this:
public class Option1 {
public Option1() : this(name) {}
public Option1(string name) {
Label.Text = name;
BackColor = Color.Green;
}
}
or
public class Option2 {
public Option2() : this(name) {
BackColor = Color.Green;
}
public Option2(string name) : this() {
Label.Text = name;
}
}
There is no functional difference between these two, it's a matter of style. I normally prefer the first option (calling the more complex constructor with default arguments) because that way all the initialisation is in one place and it's easy to confirm that you have set everything you meant to.
|
|
|
|
|
|
Hi every1. This is my first post so be gentle
I want to make ,a song organizer connected with database(sql).
So basicaly windows app with option for just inserting my favorite song names with artist/genre selection thats it..
Any similar tutorial step by step or so? Im new into c# but don't know how to start.. Help plz
|
|
|
|
|
Search around for tutorials, pick the one that uses books as a subject (assuming there is not one based on songs).
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hello.
I am working on Windows Forms Application project (it is assignment). End this is how form should look: http://postimg.org/image/ywkeyuc5f/[^]
I need to write method that when I click on Add button textboxes should be erased (so the new value which user add could be accepted).
Any suggestions?
|
|
|
|
|
Vexy wrote: Any suggestions? Try looping all the controls, and check if it's a textbox. If yes, set the Text property to nothing.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
..the buttons, the textboxes, the labels; all the stuff on the form. What UI are you targetting? WPF, WinForms, or ASP.NET?WinForms, as stated in the original post!
Your form is a container that contains a collection of different controls[^]. There's some textboxes and some buttons on your form.
If you loop over that collection (foreach), then you can inspect all the elements on a form. You can also ask a control whether it is of a specific type. If it is of the TextBox type, then cast it to one and change it's value.
If any of above three lines sound weird then we'll expand on them
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
modified 28-May-14 14:26pm.
|
|
|
|
|
There are many ways you could accomplish this, ranging from the extremely simple through to just the simple. If you're just looking to set those three TextBox controls to be empty, then the quickest way is just to explicitly set the Text property to string.Empty for each one. So, suppose you had txtForename, txtSurname and txtAge as the three TextBox es, simply do this in the event handler for the add button:
txtForename.Text = string.Empty;
txtSurname.Text = string.Empty;
txtAge.Text = string.Empty; Now, you could accomplish this by looping through all the controls on the form, and loop through all the child controls as well, looking for TextBox es, but I would stick with the simple version if I were you. Fancier implementations really are a case of YAGNI for your assignment.
|
|
|
|
|
Thank you VERY MUCH for detailed answer. I will try to do like this.
Best regards!
|
|
|
|
|
KISS. The acronym, not the action.
+5
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
you can do that by calling a function which fill the text boxes when the edit button clicked and filling the boxes when add new value button called.
Hint: use a flag to know the order type.
Osama M.Shatnawe
|
|
|
|
|
Dear reader,
at startup of my program I want to find all instances/classes, which support an special interface.
Example:
I have class A, which supports interface "void someFct()"
I have class B, which supports interface "void someFct()"
At startup of my program, I want to call both functions/interfaces without registering them before.
I hope you can understand, what I want?
Have a nice day
############### update ########################
I try to describe my problem better
My app reads a lot of data-sources and then it executes a list of ReportInstances, where each report creates excel-reports/sheets. This takes roughly 10 minutes. Each individual report checks/validates its input/config/... before it executes its own business-logic. In practice it happens, that in worst case the last report detects an error at its validation and the program stops. This is very annoying.
Simplyfied code here:
<pre>void CreateReport( params here ) {
CreateReport_1(par);
CreateReport_2(par);
.......
}
My idea is: Do validation, before starting the single reports
Solution 1: Register all validation-delegates and execute them before starting the reports
This kind of code is
void CreateReport( some params ) {
myValidationList.Add( Reporter_1.GetValidationDelegate());
myValidationList.Add( Reporter_2.GetValidationDelegate());
foreach (validationDelegate in myValidationList) {
execute validationDelegate;
}
CreateReport_1(par);
CreateReport_2(par);
.....
}
This is easy, but it has the disadvantage, that each time I add a new reporter I have to change my "registration-code". It is some kind of maintenance problem.
Solution 2: Do it "more automatic", this is what I am looking for
The kind of code I am looking for is
void CreateReport( some params ) {
myValidationList = GetAllAvailableValidationDelegates()
foreach (validationDelegate in myValidationList) {
execute validationDelegate;
}
CreateReport_1(par);
.....
}
I am looking for the code of "GetAllAvailableValidationDelegates()", which "parses" automatically all available classes/instances in my program and looks for such delegates
modified 29-May-14 0:00am.
|
|
|
|
|
|
I think learning MEF[^] can help you...
I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V)
|
|
|
|
|
Frygreen wrote: I want to call both functions/interfaces without registering them before. What does "registering" mean here? Are you referring to the examples of Unity?
You can ask a class which interfaces it implements; you'd still need to have "some place" where you define WHICH interface should be searched for.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Frygreen wrote: at startup of my program I want to find all instances/classes, which support an special interface.
Your requirement as stated in general is difficult.
However if your application is small and/or you limit the search parameters it becomes more reasonable.
As an example of the difficulty involve one wouldn't want to, for example, search all of the Microsoft API classes for your interface since it just won't be there.
So besides using reflection you should determine where you are going to search.
You should also evaluate whether this is really worth while in terms of future plans. It might be easier to look into using Windows Addins (or whatever they are called) or in just hard coding a list or even self registration.
|
|
|
|
|
Not sure why this is downvoted? Perhaps it was very bad pre-edit.
Anyway, what you are asking for is a classic plugin architecture, and that's a well solved problem. There are three steps to it:
- Create a boundary interface that defines what the plugin should do. This interface should be in an assembly available to both the plugin developer (plugins need a compile time reference to the assembly) and the application. In the case of a releasable app or something where the same team develops both sides it can go in the main application assembly.
- Create plugin classes which implement the interface and do the work.
- Write some reflection code in your main application that finds instances of the plugins in relevant assemblies, and registers them.
The exact implementation of that depends on whether you need AppDomain separation between plugins (for example if you want to support plugin update or unloading without restarting the application, or different security contexts), and whether plugins will be in separate assemblies.
In this case the boundary interface is
public interface IReportGenerator {
void Validate();
void Execute();
}
... although I'd expect some form of input to be passed to both methods in reality.
The simplest version of the reflection code (look in a single assembly only) looks like this:
public void RegisterPlugins(Assembly a) {
foreach(Module mod in a.GetLoadedModules()){
foreach(Type ty in mod.GetTypes()){
foreach(Type intf in ty.GetInterfaces()){
if(intf == typeof(IReportGenerator)){
RegisterPlugin((IReportGenerator)Activator.CreateInstance(ty));
}
}
}
}
}
For a full implementation including looking up assemblies in a directory and loading each plugin into an AppDomain, check out my game lobby article[^] (LobbyClient/GameType.cs or LobbyServer/GameTypes.cs). Although don't necessarily copy the coding style in there, that is old code from before I knew what I was doing.
|
|
|
|
|
<pre lang="c#">
string fileToLoad = @"C:\Users\nitin.jain\Documents\visual studio 2012\Projects\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
string migrationStepsDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassLibrary1.dll");
AppDomainSetup appDomainSetup = new AppDomainSetup() { PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory, ShadowCopyFiles="true" };
Evidence evidence = AppDomain.CurrentDomain.Evidence;
AppDomain appDomain = AppDomain.CreateDomain("ClassLibrary1", evidence, appDomainSetup);
Assembly assembly = Assembly.LoadFile(fileToLoad);
Type type = assembly.GetType("ClassLibrary1.Class1");
object foo = Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod("CheckAdress");
methodInfo.Invoke(foo, new object[] { "navdeep" });
AppDomain.Unload(appDomain);
Console.WriteLine("App domain unloaded");
Console.ReadLine();
This code is in console application and it works fine in the sense that it loads and unload the assembly in the domain.
But when my console is running and i try to delete the dll it says that dll is opened in console application.
So it is locked by it. How can i make sure that after unloading it, also unlocks the file.
|
|
|
|
|
Assembly assembly = Assembly.LoadFile(fileToLoad);
The assembly object is still in memory, so it is most likely holding an open handle to the file. You could try to dispose of it to see if that releases the file.
|
|
|
|