Reputation: 95
I am experimenting(First timer!) with external assemblies, and whenever I call a method from my external assembly I get all empty data... here are some snippits: External assembly called like this:
FileOps.Outs O = new FileOps.Outs();
FileOps.ReadFile(LOC); // LOC = Filepath
foreach (string S in O.FileContainer) // O.FileContainer is List<string>
{
Console.WriteLine(S); // Prints Nothing
}
Readfile() method in assembly:
public static Outs ReadFile(string LOC)
{
Outs O = new Outs();
if (File.Exists(LOC))
{
foreach (string S in File.ReadLines(LOC))
{
O.FileContainer.Add(S);
}
O.Baal = true;
}
else
{
//O.Baal = false;
//O.FileContainer.Contains(null);
File.Create(LOC).Close();
string Header = "Useless text data here\n," + "Users:\n,";
O.FileContainer = new List<string>(Header.Split(O.Csep, StringSplitOptions.None)); //Csep is char[] {','}
foreach (string S in O.FileContainer)
{
File.AppendAllText(LOC, S);
}
}
return O;
}
Class used to store info:
public class Outs
{
public bool Baal { get; set; }
public List<string>FileContainer { get; set; }
public char[] Csep;
public Outs()
{
Baal = false;
FileContainer = new List<string>();
Csep = new char[] { ',' };
}
}
Upon returning to calling method all values are 0 or null... I have set a breakpoint and went through the code line by line. Prior to returning all data is good... any thoughts?
Upvotes: 0
Views: 94
Reputation: 52210
Instead of
FileOps.Outs O = new FileOps.Outs();
FileOps.ReadFile(LOC); // LOC = Filepath
Try this:
FileOps.Outs O = FileOps.ReadFile(LOC);
It's a static method that returns an instance. The caller isn't meant to use new
to create their own instance.
If you are in control of the FileOps
class, you can prevent the caller from making this mistake by marking the constructor private, e.g.
public class Outs
{
private Outs()
{
//etc.
This way, the static method ReadFile
has the ability to create a FileOps (because it is a member of the class), but nobody outside of the class can instantiate one. This is a pretty common pattern.
Upvotes: 2