C# Why use CultureInfo.InvariantCulture for such a simple task [duplicate] - c#

This question already has answers here:
Is Int32.ToString() culture-specific?
(7 answers)
Closed 7 years ago.
Ok i am going through Saplo Api C# project. It stump me when i saw these code:
public class Helper
{
private static int _currentId;
public static int GetCurrentId()
{
return _currentId;
}
public static int GetNextId()
{
return ++_currentId;
}
}
[DataContract]
internal class RequestBase<T>
{
public RequestBase()
{
ID = Helper.GetNextId().ToString(CultureInfo.InvariantCulture);
}
public RequestBase(string method, T #params)
: this()
{
Method = method;
Parameters = #params;
}
[DataMember(Name = "id")]
public string ID { get; private set; }
[DataMember(Name = "method")]
public string Method { get; set; }
[DataMember(Name = "params")]
public T Parameters { get; set; }
}
So if you look at the constructor for RequestBase.... public RequestBase()! you will see Helper.GetNextId() this only return an int why bother using CultureInfo.InvariantCulture i dont understand why a simple ToString inst good enough to do the job or what, isnt this is just more overhead?

When it comes to integers, there is currently no recognized, official culture that would affect how Int32.ToString() behaves. It will always create an identical string.
However, that does not mean that a custom culture might not interpret the results differently. Resharper and other code style tools typically recommend using a culture to maintain consistency.
It is worth noting, when travelling outside of integers, cultures absolutely make a difference. For instance, in EN-US, commas are used for thousands separation and periods are used to represent the decimal point. On the other hand, in EN-GB it's the opposite. Keeping consistency between value types could certainly be viewed as a good habit.
That said, in this case, yes, providing CultureInfo for integers is probably unnecessary "overhead", unless you prefer to keep consistency in your codebase.

In this case it doesn't seem necessary. I know plugins like ReSharper and StyleCop will complain(show a warning) about an empty ToString() unless you tell them not to. It's possible one of these plugins was used when writing this code.
Generally CultureInfo.InvariantCulture is used when converting dates and decimal/currency values.

Related

Is a struct with the format 1.0.0 possible?

So I'm playing around a bit with the possibilities of modules for an application I'm building and I'd like to version them.
These modules which are dlls implement an interface with a property for the version of this module. The format should be "Major.Minor.Build".
If I create a property of type String, the possibility of a version like "Major.Minor" or "Major.Minor.Build.Revision" exists. I want to prevent that.
So I had the idea of a struct like Double but with a third digit. My question is now, is this even possible and if yes, how can I implement something like this?
In the class it should look like this:
public class MyModuleContext : IModuleContext
{
public ModuleVersion Version { get; set; } = 1.0.0;
// more interface things ...
}
Thanks for your help :)
Just create a class that meets your needs:
public class Version: IVersion
{
public int Major { get; }
public int Minor { get; }
public int Build { get; }
public override string ToString =>
$”{Major}.{Minor}.{Build}”
public Version(int major, int minor, int build)
{
//omitted argument validation
Major = major;
Minor = minor;
Build = build;
}
}
If you are mainly going to be passing IVersion references around, you are better off implementing this as a reference type or you’ll be boxing the value type all over the place.
It’s up to you if you want to implement value equality semantics, comparison logic, etc. It’s all pretty trivial.

Different ways to declare properties [duplicate]

This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
What is the difference between a field and a property?
(33 answers)
Closed 7 years ago.
Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?
CASE 1:
private static int number = 1;
public static int Number
{
get { return number; }
set { number = value; }
}
CASE 2:
public static int Number
{
get;
set;
}
I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.
The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.
Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.
We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:
private int mNumber;
public int Number
{
get
{
return Number;
}
set
{
if (Number == 8)
{
throw new CannotReceive8Exception();
}
else
{
mNumber = value;
}
}
}
If you look at the decompiled code of this code:
public int Number { get; set; }
You will see that the compiler has added a background private field anyway:
While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use
public int Num {get;set;}
in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.

Is it architecturally wrong to use dynamic return type on a method exposed through interface? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a method that is exposed using interface in the business logic layer. It is as follows:
public interface IMyWorkingClass
{
IEnumerable<dynamic> GetSomeList();
}
public class MyWorkingClass : IMyWorkingClass
{
public IEnumerable<dynamic> GetSomeList()
{
dynamic foos = new List<dynamic>();
dynamic item = new ExpandoObject();
item.PropOne = (new Foo()).FooPropertyOne;
item.PropTwo = (new Bar()).BarPropertyOne;
foos.Add(item);
return foos;
}
}
public class Foo
{
public int FooId{get;set;}
public string FooPropertyOne{get;set;}
public string FooPropertyTwo{get;set;}
}
public class Bar
{
public int BarId{get;set;}
public string BarPropertyOne{get;set;}
public string BarPropertyTwo{get;set;}
}
There are a lot of different opinions/preferences out there about dynamic itself. I find them useful. One of my friends said dynamics are good but the way they are used above are not. The argument presented was that the compiler wont catch the things changed on dynamic object. I think the unit tests will be able to catch those. So I disagreed. What is your expert opinion? Thanks in advance :)
Update
Here's bit clearer (hopefully) code:
public interface IMyWorkingClass
{
IEnumerable<dynamic> GetListOfClassesForStudentDynamicReturn();
IEnumerable<StudentClassInfo> GetListOfClassesForStudentStaticReturn();
}
public class MyWorkingClass : IMyWorkingClass
{
public IEnumerable<dynamic> GetListOfClassesForStudentDynamicReturn(Student student)
{
dynamic listOfClasses = new List<dynamic>();
// repository pattern is used in DAL
var datafromDB = (StudentCollegeClassRepo.GetQueryable(x=>x.StudentId==student.StudentId)
.select(item => new {
item.CollegeClassId
,item.CollegeClass.CollegeClassName
,item.IsEnabledForStudent
}).ToList();
foreach (var item in datafromDB)
{
dynamic classWithStudent = new ExpandoObject();
classWithStudent.CollegeClassId = item.CollegeClassId;
classWithStudent.CollegeClassName = item.CollegeClassName;
classWithStudent.IsEnabledForStudent = item.IsEnabledForStudent;
listOfClasses.Add(studentWithClass);
}
return listOfClasses;
}
public IEnumerable<StudentClassInfo> GetListOfClassesForStudentStaticReturn(Student student)
{
// repository pattern is used in DAL
var datafromDB = (StudentCollegeClassRepo.GetQueryable(x=>x.StudentId==student.StudentId)
.select(item => new StudentClassInfo {
CollegeClassId = item.CollegeClassId
,CollegeClassName = item.CollegeClass.CollegeClassName
,IsEnabledForStudent = item.IsEnabledForStudent
}).ToList();
return datafromDB;
}
}
// this class is like a viewmodel
public class StudentClassInfo
{
public int CollegeClassId { get; set; }
public string CollegeClassName { get; set; }
public bool IsEnabledForStudent { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
}
public class StudentCollegeClass
{
public int StudentId { get; set; }
public int CollegeClassId { get; set; }
public bool IsEnabledForStudent { get; set; }
}
public class CollegeClass
{
public int CollegeClassId { get; set; }
public string CollegeClassName { get; set; }
}
Hopefully I made things little clearer now. So,method with dynamic return is ok or create a static type and have that returned instead? I am also learning how to ask question properly here.. Thanks for your patience and awesome replies :)
Despite what Skeet says :) I'll add some thoughts here.
If you start down the path of using Dynamics, you must shift your thinking. You don't know what your object is, you only care about what it can do.
You find yourself not needing interfaces rather quickly - and then you ask yourself "WTF am I doing anyway?". Which is always a great question to ask.
And then a shift happens as you start writing more tests to cover up the loss of a compiler check - you start writing methods a bit more clearly. You start relying on Factories and other classes to impose logic on top of these little bits of amorphous dynamic goo.
It's incredibly freeing if you consider the mental shift. For instance you have a "MyWorkingClass" that does something on top of Foo/Bar. If that was a fulfillment class called "Warehouse" that had some methods called "CheckInvetoryOf(dynamic item)" - things start to make a bit more sense.
In the real world you would send in an interface here - probably ITrackable or something - that exposes a very very small subset of what could be used. It would work, but what if you changed your approach later and wanted the Warehouse to ship digital goods - something like downloads?
Your Warehouse class was probably fashioned after a brick and mortar - and making the shift to sending out digital downloads... OH NO!
But if you use dynamics - it's easy. You could simply ask if the item has is an IDigitalGood (for instance) and handle it nicely.
So - the code you wrote is, yes, confusing. If you spend some time with Dynamic languages it will afford you the mental shift to make it not so confusing.
Oh - in terms of "Architecturally Wrong" to do what you did... who knows. If it's confusing, that's not good. If it makes testing hard - that's triple not good. If you get laughed at, you might be on the right track :)
So, you want to create an interface that expose a method that return an unknown IEnumerable? Is there a direct advantage in using the generic version of IEnumerble in this case beside saving some cast/test/overload that you would have to do anyway if you want to use those objects after the method is returned?
While I won't dispute that dynamic can be useful in some case. In my opinion, it often displays a design flaw. Every time I came to use it, I actually sat down and thought if I really needed it. And most of the time, I came to the conclusion that with some simple changes, I could eliminate it and make a cleaner design.
In this case, do you truly need to have a generic type with dynamic? My first and quick guess would be, you can probably use the non-generic IEnumerable.
Or if you want to save some casting, and you have different elements in there, you can find common ground to all element. I see that right now, all your property are string. Or if you want to return combination of elements, you can use some Tuple<>
If you truly end up returning a complete unknown types of lot of different objects, you could use IEnumerable<object>, but then I would question the reason of existence of that interface implementation. I don't remember ever creating an interface that would return object with absolutely any kind of common ground between the different implementation, or even within a single implementation. It could controls, numbers, components, entities... But they tend to share something. If it's properties, you could even pack in some PropertyInfo!
TL:DR; Unless you can present a very clear case where this design pattern would serve a very specific purpose that is unavoidable by any other means, I would recommend not using it. My IEnumerable of 2 cents.

Pattern for reverse-accessible logic changes?

I'm trying to find a design pattern or a best practice, or some other solution for a problem with keeping back versions of business logic within my application. Specifically, I am looking to find a way to determine which logic was used to issue an insurance policy.
I currently have code which looks like this:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium();
return (base_premium * percent);
}
I am needing to make a change to the business logic so that this function looks more like:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium() + MedicalPremium();
return (base_premium * percent);
}
Where I run into trouble is that existing policies should rate with the previous logic. Is there a design pattern for this? If not, are there any good ways to implement it?
Strategy pattern sounds most applicable. Probably you'd need a factory method or some such that takes in a date to return the appropriate strategy.
You're going to have to use additional data of some form to keep track of precisely what algorithm was used to obtain your data; you'll probably need to change your persistence representation to maintain versioning information about the algorithm used to derive your results.
BTW, you might consider making things like MedicalPremium or TheftPremium a Get-only property, rather than a parameterless function. They fit that paradigm very well.
There are any number of ways you can solve this problem. Some examples:
1) Switch to the new code and add a flag to the user data so that MedicalPremium automatically returns 0 for old users. This is particularly easy if you stored your data in XML; the old data just won't have the flag, and it won't affect your deserialization of the data because XML is flexible.
2) Make the class that contains your function MedicalPremium a base class, and make MedicalPremium virtual. Override it in the derived class, which is your new version. Newer users are the derived class. Old users are created as the base class. For the old users, it always returns 0. Properties can also be virtual just as functions can.
If you have a chance to look at Martin Fowler's Patterns of Enterprise Architecture he talks about individual instance methods, which isn't entirely the same as what you have, but is very similar. It's a great book in any case.
In the meantime, I think you might have to start considering your functions as also being data, and store in your database which function was used. You don't need (but may want) to store the function text, but you do need enough information to determine at run time which method to call. You asked about patterns, and obviously you have a strategy pattern going on here, which you could reference, but I don't know if it will be especially helpful.
Yes there is: the Decorator Pattern. You can use this to extend the behavior of a class with additional wrapper classes. In the example below I combine this with the Template Method Pattern to achieve what I believe you are looking for.
public class BaseSurchargePolicy {
protected abstract double BasePremium { get; }
protected abstract double FixedDeductibleSurchargePercent { get; }
public double FixedDeductibleSurchageAmount{
get
{
return (BasePremium * FixedDeductibleSurchargePercent);
}
}
protected ICollection<string> _ProcessorsUsed;
public IEnumerable<string> ProcessorsUsed
{
get { return ProcessorsUsed; }
}
}
public class OldSurchargePolicy : BaseSurchargePolicy
{
protected double BasePremium
{
_ProcessorsUsed.Add(GetType().Name);
return CollisionPremium + TheftPremium;
}
protected double FixedDeductibleSurchargePercent { get; set; }
public double CollisionPremium { get; set; }
public double TheftPremium { get; set; }
}
public class MedicalSurchargeDecorator: BaseSurchargePolicy
{
private BaseSurchargePolicy _wrapped;
private double _medicalPremium;
public MedicalSurchargeDecorator(BaseSurchargePolicy wrapped, double medicalPremium)
{
_wrapped = wrapped;
_medicalPremium = medicalPremium;
}
protected double BasePremium
{
get
{
_ProcessorsUsed.Add(GetType().Name);
return _wrapped.BasePremium + _medicalPremium;
}
}
protected double FixedDeductibleSurchargePercent {
get { return _wrapped.FixedDeductibleSurchargePercent }
}
}

Are there any more benefits, or perhaps drawbacks of the "new" way to define properties? [duplicate]

This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
Closed 9 years ago.
Are there any further benefits to the "new", shorter way to handle properties, other than shorter code - like performance benefits, less memory usage etc.?
Writing
public string StrVariable { get; set;}
Rather than
private string strVariable;
public string StrVariable
{
set
{
strVariable = value;
}
get
{
return strVariable;
}
}
And are there any drawbacks - perhaps some would argue the code is less readable, less explicit?
Heres a link you may find useful.
One big drawback in a specific scenario - you lose control of the field name. This might sound insignificant, but it is a big problem if you are using binary serialization (via BinaryFormatter).
Other things:
they can't be readonly at the field level
for structs you need to call : this() in custom constructors
They do, however, do a fantastic job in 99% of cases - they express the code neatly, while leaving it possible to add extra implementation details later (by switching to explicit fields) without breaking calling code (except for the points above).
One drawback I can see is if you want to do something else in the get/set routines. Increment a counter or something of that sort. Maybe validate the input if you haven't already.
Collection properties are one issue as well. They are not initialized with Autoproperties.
Example:
public class foo
{
public List<String> S1 { get; set; }
private List<string> s = new List<string>();
public List<String> S2
{
get { return s;}
set { s = value; }
}
}
foo f = new foo();
f.S1.Add("thing");
f.S2.Add("thing");
f.S1.Add will bomb with a nullref exception.

Categories