I come across a change in a program which my current infastructure couldn't handle and was become too long: I had to stop using such absolute code and move towards Object Orientated.
Repetition issue:
List<string[]> logos = new List<string[]>();
string[] tempLogo = new string[2];
tempLogo[0] = "FRONT EMB";
tempLogo[1] = front_emb;
logos.Add(tempLogo);
tempLogo[0] = "back EMB";
tempLogo[1] = back_emb;
logos.Add(tempLogo);
Became:
delegate string addLogo(string x); // Namespace area
public static void IntergrateLogo(string toAdd, string name) // Inside Class
{
string[] tempLogo = new string[2];
tempLogo[0] = name;
tempLogo[1] = toAdd;
logos.Add(tempLogo);
}
// Main method
addLogo adl = new addLogo(IntegrateLogo);
List<string[]> logos = new List<string[]>();
adl(front_emb,"FRONT EMB");
adl(back_emb,"BACK EMB");
Issue:
1. The name 'logos' does not exist in the current context
2. No overload for 'IntergrateLogo' matches delegate 'addLogo'
3. Embedded statement cannot be a declaration or labeled statement
Question:
From my, very low, knowledge on delegates, they should 'mimic' the main method environment; therefore, my List - logos
, should be able to be seen and used inside the IntergrateLogo
method.
Well, that understanding went out the window when I couldn't get this working.
I am not asking for a fix here, I just want a better understanding with delegates because everywhere I search, it says that it allows the context environment scope to be accessed within a method but clearly that is not working here.
Is there a way that logos
can be seen within the IntergrateLogo
method by using a delegate?
Is there a way that logos can be seen within the IntergrateLogo method by using a delegate?
Not when it's a local variable, no.
It's not really clear why you'd use delegates for this at all though. I wouldn't even use a method, but instead write:
List<string[]> logos = new List<string[]>
{
// TODO: Rename front_emb and back_emb to follow .NET naming conventions
new[] { front_emb, "FRONT EMB" },
new[] { back_emb, "BACK EMB" },
};
I'd also consider creating a Logo
class rather than using string arrays, at which point you'd have:
List<Logo> logos = new List<Logo>
{
new Logo(front_emb, "FRONT EMB"),
new Logo(back_emb, "BACK EMB"),
}
That's looking considerably tidier, IMO.
See more on this question at Stackoverflow