Get some unique name per each run of the console application [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Not sure how to ask this. I am writing a CONSOLE app in C#. With each run I plan to create an output txt file. However I need some expression that will give an unique name with each run ( and also this name must remain the same through out the run ) I can use YYYYMMDDSS but this can change with each call. So you see what I mean. It should be something like Session ID ( I don't know what method/function will give me this ). Help please ? ( I am new to C# )

If you want the identifier to change on each execution, but be consistent for the life of the program, you probably want to generate it once and store the result.
One way is to store it in a readonly static property:
public static class RuntimeIdentifier
{
public static string Value { get; } = DateTime.Now.ToString("yyyyMMddhhmmss");
// Notice this is NOT the same as:
//
// public static string Value { get { return DateTime.Now.ToString("yyyyMMddhhmmss"); } }
//
// which will return a NEW value each time you access it
}
Another way would be to use Lazy<T>, which computes a value the first time you access it, and returns the same value each time after that.
public static class RuntimeIdentifier
{
public static Lazy<string> _identifier = new Lazy<string>(() => DateTime.Now.ToString("yyyyMMddhhmmss"));
public static string GetValue()
{
return _identifier.Value;
}
}
If it's important that the value be generated immediately when the app is started, you can generate and save it explicitly:
class Program
{
public static void Main()
{
RuntimeIdentifier.Value = DateTime.Now.ToString("yyyyMMddhhmmss");
// ...
}
}
public static class RuntimeIdentifier
{
public static string Value { get; set; }
}

Your scenario is not totally clear but if you are just trying to create a txt file with unique name each time you run your application than you should use Path.GetRandomFileName() for that matter. Or just look how it's implemented and adapt it to your needs.

Related

Cannot convert from '...Generic.List<Game02.Human>' to 'Game02.Human' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make functions to "send" NPCs to specific rooms by adding them to the room's humansHere list, and one to get this list (and print it later, but I don't need help with that). But I get this error message:
Argument 1: cannot convert from 'System.Collections.Generic.List<Game02.Human>' to 'Game02.Human'
Once I get that fixed, I'm sure I'll figure out the rest, so feel free to ignore this: I need to know how to call this function for specific rooms. Something like:
LivingRoom.GetHumansHere() or Kitchen.SetHumansHere(_lyndonJohnson). Or will this work as it is?
public class Room
{
public int ID { get; set; }
[...]
private List<Human> humansHere;
public List<Human> GetHumansHere()
{
return humansHere;
}
public void SetHumansHere(List<Human> x)
{
humansHere.Add(x);
}
}
public class Human : LivingCreature
{
public int Gold { get; set; }
public List<InventoryItem> Inventory { get; set; }
public Human(string name, int currentHitPoints, int maximumHitPoints, int gold) : base(name, currentHitPoints, maximumHitPoints)
{
Gold = gold;
}
}
Thank you to Dmitry for making it work, and thank you to Jonathan for explaining the problem:
The problem is you are trying to add a LIST of humans to a list rather than a single human to a list
Two possibilities:
If you want to add one person only, change method's signature:
public void SetHumansHere(Human person)
{
if (null == person)
throw new ArgumentNullException(nameof(person));
humansHere.Add(person);
}
If you want to add a collection of persons in one go, use AddRange
// IEnumerable<Human> - let's generalize the method
// and allow to add not only List, but other collections, say, array
public void SetHumansHere(IEnumerable<Human> persons)
{
if (null == persons)
throw new ArgumentNullException(nameof(persons));
humansHere.AddRange(persons);
}
you need to use List.AddRange, Adds the elements of the specified collection to the end of the List.
public void SetHumansHere(List<Human> x)
{
humansHere.AddRange(x);
}

Is there a good practice of setting default values in an constructor? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Consider a simple class
public class MyClass
{
private int myProperty
...
public int MyProperty
{
get
{
return myProperty;
}
set
{
// some evaluation/condition
myProperty= value;
}
}
...
}
Now, if I want to create an empty constructor where I set default values for the class properties I could do this either this way:
public MyClass()
{
myProperty = 1;
...
}
or this way:
public MyClass()
{
MyProperty = 1;
...
}
Both examples seem valid, since I would never set a default value, that doesn't meet the requirements in the setter evaluation.
The question is, is there a best practice or doesn't it matter anyway?
What would be the advantage of one or the other be (as I can't find any)? Is there some reference, where this question is adressed?
So far I have come across code from many different developers that use either or both ways...
You can use both. But i prefer the first one. Why? Because the value that the property uses is directly assigned. For C# 6 above, you can use default value in a property directly without using constructor.
public class Person
{
public string FirstName { get; set; } = "<first_name>";
public string LastName { get; set; } = "<last_name">;
}
I personally like to set it as you done in first block.
For me it serve as additional fact of method is constructing object, not using alredy constructed. Also it makes me sure that properties is not called (they transform to set/get functions which results in couple of excess instruction).
But i believe that both variants are valid and maybe compiler optimizes properties to direct assignment.
For simple data first method is ok. But on more complex data, you could have a condition in the set (depending to another variable for example, set { if (Config.TestEnv) ...} so if you directly set the private value, you could be in trouble.

Multiple delegate assignments and call in a C# card game action sctruture [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm working on an Card Game development in C#, and I don't know how to do the following:
I have my Card class, which has a List of actions that are attacks in which that card can perform.
These attacks are a custom class named Act (in which I called Rules in the example).
When I load my cards I call an Inicialize method that I created that inicialize the List of cards, as well as the List of Attacks of each card.
I Want to be able to express my Attacks as an multiple Method call with parameters that will be called only when I call that Attack for execute.
For example, something like that
ActionList = new List<CardRule>();
ActionList.Add(new CardRule()
{
Description = "Cause 20 damage, then causes burn status.",
Rules = Damage(20).CauseStatus(Status.Burn);
});
I want to define the action(which I called Rules) as an multiple method call, passing parameters,
And call that Rules.Execute() to perform all method call, etc..
I Know that its something related to delegates, but I don't know how to do this calling multiple methods with predefined parameters.
Thank you in advance and sorry for bad english, I'm new at Stack Overflow also..
Regards,
What you're looking for isn't actually a delegate, but a class which tracks what needs to be done. This is a pattern used often by fluent APIs, but it's relatively simple to create something for your example.
For your example, you may have an IActionConfiguration interface, for example:
public interface IActionConfiguration
{
void PerformAction(MyTarget target);
}
Now, you'll want a few different implementations. For example, one which represents damage:
class DamageActionConfiguration : IActionConfiguration
{
private int m_damageStrength;
public DamageActionConfiguration(int strength)
{
m_damageStrength = strength;
}
public void PerformAction(MyTarget target)
{
target.Health -= strength;
}
}
And another one to represent a status effect:
class CauseStatusActionConfiguration : IActionConfiguration
{
private Status m_status;
public CauseStatusActionConfiguration(Status status)
{
m_status = status;
}
public void PerformAction(MyTarget target)
{
target.StatusEffects.Add(m_status);
}
}
Now, you'll also one an implementation which represents multiple actions.
class CompositeActionConfiguration : IActionConfiguration
{
private IActionConfiguration m_firstWrappedConfiguration;
private IActionConfiguration m_secondWrappedConfiguration;
public CompositeActionConfiguration(IActionConfiguration first, IActionConfiguration second)
{
m_firstWrappedConfiguration = first;
m_secondWrappedConfiguration = second;
}
public void PerformAction(MyTarget target)
{
m_firstWrappedConfiguration.PerformAction();
m_secondWrappedConfiguration.PerformAction();
}
}
This is incredibly simplified, but good enough for our example. Now you have a class (CompositeActionConfiguration) which can represent multiple actions - all you need is the magic that lets you chain them together easily.
public static class ActionRules
{
//First, you want a few static methods which can start a chain:
public static IActionConfiguration Damage(int strength)
{
return new DamageActionConfiguration(strength);
}
public static IActionConfiguration Status(Status status)
{
return new CauseStatusActionConfiguration(status);
}
// Next, some extension methods which allow you to chain things together
// This is really the glue that makes this whole solution easy to use
public static IActionConfiguration WithDamage(this IActionConfiguration source, int strength)
{
return new CompositeActionConfiguration(source, Damage(strength));
}
public static IActionConfiguration WithStatus(this IActionConfiguration source, Status status)
{
return new CompositeActionConfiguration(source, Status(status));
}
}
That's it. This gives you a solution which does more or less what you want. You would define your Rules property as an IActionConfiguration, then you can consume it like this:
var card = new CardRule()
{
Description = "Cause 20 damage, then causes burn status.",
Rules = ActionRules.Damage(20).WithStatus(Status.Burn);
};
card.PerformAction(target);

Dictionary containing List [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The below code:
public struct Value
{
List<string> RFcode;
int found;
int expected;
public int Found { get { return found; } }
public int Expected { get { return expected; } }
public List<string> Code { get { return RFcode; } }
public Value(int f, int exp, string s)
{
this.found = f;
this.expected = exp;
RFcode.Add(s);
}
}
is Invalid. On VS debug I get :
Error 1 Field 'BE_EOR.InvCyclic.Value.RFcode' must be fully assigned before control is returned to the caller
Error 2 Use of possibly unassigned field 'RFcode'
Please try this one:
List<string> RFcode = new List<string>();
The reason, why you get this error is the fact, that you haven't created a list, which will hold the strings you want. However, you try to add elements in this list:
RFcode.Add(s);
This line of code, List<string> RFcode;, it justs defines a variable called RFcode, that will keep a reference to a List of strings. Neither it creates a list nor it assings it to this variable.
Update
As already Christian Sauer has pointed out and Kensei have reminded it to us, it would be better you use a class rather than the struct you use:
public class Value
{
public List<string> RFCode { get; set; }
public int Found { get; set; }
public int Expected { get; set; }
public Value(string s, int found, int expected)
{
RFCode = new List<string> { s };
Found = found;
Expected = expected;
}
}
However, at this point I have to raise a question. Why are you using a List of strings, since you only pass a string to your constructor? If that's the case, to pass only a string, I don't think that's a good design, since you don't use the most appropriate type for that you want.

C# type design Question [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
This might sound a little stupid but I am still curious about what the community thinks.
So I have a WebService returning a UpdateInfo class.
Now consider the following definitions
public enum TTCFileType
{
API = 0,
BOOKMARK,
TICKMARK
}
public class FileUpdateInfo
{
public string FileName;
public string FileDownLoadURI;
public TTCFileType FileType;
}
public class UpdateInfo
{
public FileUpdateInfo fuInfo;
//Other
}
Here is the issue, if the TTCFileType has the value TICKMARK then I need another enum viz Tickmark Type( the biz logic demands this information). I am wondering what is the best way to represent that. I dont want a method signature where I have something Like
UpdateMethod( UpdateInfo ui, TickMarkType tt)
where I examine tt if ui.fuInfo.FileType == TTCFileType.TICKMARK
I guess I am trying to find an semi elegant way at least to represent the conditional requirement for getting the second piece of information out ( in many ways this so reminds of VARIANTS , if var.VT == VT_[thingy] then use vt.[thingy] and yes I know how c# developers feel about unions :-)
Anyway curious if there is a nifty way to do this
Thanks
Just include TickMarkType field to FileUpdateInfo class?
I'd be tempted to go with something like:
public enum TTCFileType
{
API = 0,
BOOKMARK,
TICKMARK_TYPE1 = 100,
TICKMARK_TYPE2 = 101,
TICKMARK_TYPE3 = 102
}
and so on. Depending on how many there are and how manageable it would feel within the wider context of your code.
Ideally, you need two additional structure(s)
public enum TickmarkType
{
TYPE1=0,
TYPE2
}
public class TickMarkFileUpdateInfo : FileUpdateInfo
{
public TickmarkType type;
}
And then read about polymorphism in web services
Store the enum value as an int. Add some offset to the value for your second enum (e.g., 1000) so that if the value is from the first enum it's 0..2 and if it's from the second enum it's 1000.1010 or whatever. Then you can set 2 properties, one that returns a nullable TTCFileType and the other that returns a nullable TickType, to read and write the values into the int field.
It seems like you're trying to use only data structures, when using OO features (such as inheritance) might help you. Maybe this example code gives you some ideas:
public class Update
{
// ... ?
}
public class FileUpdate : Update
{
public virtual string Name { get; set; }
public virtual string DownloadUri { get; set; }
public virtual bool IsTickMarked { get; set; }
}
public class ApiFileUpdate : FileUpdate
{
// ...
}
public class BookmarkFileUpdate : FileUpdate
{
// ...
}
You can still serialize these, given the proper serialization attributes.
In fact, you can define (potentially virtual) methods on these various classes, and actually use them to implement your program.
Overly segregating your data and code is known as the Anemic Domain Model Anti-Pattern.

Categories

Resources