Reputation: 2393
private static void print(StreamWriter sw, string mlog, bool screen)
{
DateTime ts = DateTime.Now;
sw.WriteLine(ts + " " + mlog);
if (screen == true)
{
Console.WriteLine(mlog);
}
}
I would use print (sw,"write here", false)
to call. 90% chance I will use false. how to make it the default to be false that way I dont have to do the extra type when I do the call?
Upvotes: 0
Views: 287
Reputation: 161
private static void print(StreamWriter sw, string mlog = "Write here", bool screen = false)
{
DateTime ts = DateTime.Now;
sw.WriteLine(ts + " " + mlog);
if (screen == true)
{
Console.WriteLine(mlog);
}
}
Upvotes: 1
Reputation: 33738
The answers involving optional parameters will work, but some languages do not support optional parameters, so they could not call this method from a public-facing API.
I would go with method overloading..
private static void print(StreamWriter sw, string mlog) {
print(sw, mlog, false);
}
private static void print(StreamWriter sw, string mlog, bool screen) { ... }
Upvotes: 1
Reputation: 5042
If you aren't using C# 4, create a function overload:
private static void Print(StreamWriter writer, string log)
{
Print(writer, log, false);
}
Upvotes: 1
Reputation: 100620
For older versions you can simply provide 2 overrides:
private static void print(StreamWriter sw, string mlog)
{
print(sw,mlog, false);
}
Upvotes: 1
Reputation: 2804
private static void print(StreamWriter sw, string mlog)
{
print(sw, mlog, false);
}
Upvotes: 1
Reputation: 1503290
If you're using C# 4, you can make screen
an optional parameter:
// Note: changed method and parameter names to be nicer
private static void Print(StreamWriter writer, string log, bool screen = false)
{
// Note: logs should almost always use UTC rather than the system local
// time zone
DateTime now = DateTime.UtcNow;
// TODO: Determine what format you want to write your timestamps in.
sw.WriteLine(CultureInfo.InvariantCulture,
"{0:yyyy-MM-dd'T'HH:mm:ss.fff}: {1}", now, log);
if (screen)
{
Console.WriteLine(mlog);
}
}
Upvotes: 7
Reputation: 12128
Just use = false
:
private static void print(StreamWriter sw, string mlog, bool screen = false)
Here's a little more info on Named and Optional Arguments in C#.
Note that this is new in C# 4.0. For older versions, use method overloads as others have suggested.
Upvotes: 1