I can't say I tried everything as I am not too much in to ASP.NET. I even tried googling but I was unsure what to search.
I haev several classes in ASP.NET as I am making a billing software for a reputed PSU. The project is deployed and is working fine.
Now the client requires the numbers in the bills to be currency formatted in reports but to be unformatted (numeric) in certain other things.
As I already have classes which have exposed property as double, I want my developers to give something very easy so that they can do it rapidly.
Something like : myclassobj.EnergyBillAmount().toCurreny("en-IN") or something like this.
Any suggestions?
All you need is Extension Method
public static class FormatExtensions
{
public static string ToCurrency(this double value, string culture)
{
//return converted value
}
}
Use Extension Methods
Create a class as below
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int ToCurrency(this Int val)
{
//Code logic
}
}
}
And do a
using ExtensionMethods;
where you want to call it
and use like
int s = 100;
int i = s.ToCurrency();
Hope it helps....
You should write extension method for that.
Instead of double you should use decimal for currency.
Do you really need an extension method for this:
string c = 1234.56m.ToString("C", CultureInfo.CreateSpecificCulture("en-IN"));
Result: ₹ 1,234.56
myclassobj.EnergyBillAmount().ToString("C2", yourCulture);
Related
Hi so I'm trying to convert a string named compToAdd into a type and im not sure how to do it, I tried googling for almost 5 hours now and here I am.
The goal would be to make slot.AddComponent<compToAddType>(); run properly
Here is a snippet of the code:
public string foundationComp;
public string turretComp;
public void buildFoundation()
{
Build(foundationComp);
}
public void buildTurret()
{
Build(turretComp);
}
public void Build(string compToAdd)
{
Type compToAddType = Type.GetType(compToAdd); //I thought this line would convert the string into a type
slot.AddComponent<compToAddType>(); // but then I get an error here saying that compToAddType is a variable thats being used like a type..so how am I supposed to convert it?
//just note that 'slot' here have no problem and is a gameobject the problem is on the word 'compToAddType'
}
Thank you in advance.
In general see Type.AssemblyQualifiedName.
If you don't have that you will need to at least have a reference to the Assembly in question and then use Assembly.GetType.
You can also get the assembly if you know at least one type from the according assembly via Assembly.GetAssembly(theKnownType)
That said, you can not use the generic version GameObject.AddComponent<T>() since the type-parameter of generics need to be compile-time constant!
You can however simply use the non-generic version of GameObject.AddComponent(Type)
public void Build(string compToAdd)
{
Type compToAddType = Type.GetType(compToAdd);
slot.AddComponent(compToAddType);
}
(Actually there even was an overload directly taking a string as parameter but it was deprecated.)
Finally I personally would avoid it completely if possible! Instead of relying on your strings being correct, why not rather use e.g.
public void buildFoundation()
{
slot.AddComponent<FoundationComponnet>();
}
public void buildTurret()
{
slot.AddComponent<TurretComponent>();
}
This is probably an incredibly dumb question but: I have a function that takes in a string, and I want to make sure that the string is a constant from a specific class. Essentially the effect I'm looking for is what enums do:
enum MyEnum {...}
void doStuff(MyEnum constValue) {...}
Except with strings:
static class MyFakeStringEnum {
public const string Value1 = "value1";
public const string Value2 = "value2";
}
// Ideally:
void doStuff(MyFakeStringEnum constValue) {...}
// Reality:
void doStuff(string constValue) {...}
I know this can technically be achieved by doing some thing like
public static class MyFakeStringEnum {
public struct StringEnumValue {
public string Value { get; private set; }
public StringEnumValue(string v) { Value = v; }
}
public static readonly StringEnumValue Value1 = new StringEnumValue("value1");
public static readonly StringEnumValue Value2 = new StringEnumValue("value2");
}
void doStuff(MyFakeStringEnum.StringEnumValue constValue) {...}
But it feels kind of overkill to make an object for just storing one single value.
Is this something doable without the extra code layer and overhead?
Edit: While a enum can indeed be used for a string, I'd like to avoid it for several reasons:
The string values may not always be a 1:1 translation from the enum. If I have a space in there, different capitalization, a different character set/language, etc. I'd have to transform the enum in every function where I want to use it. It might not be a lot of overhead or a performance hit in any way, but it still should be avoided--especially when it means that I'm always mutating something that should be constant.
Even if I use a separate string array map to solve the above function, I would still have to access the translations instead of just being able to use the enum directly. A map would also mean having two sources for the same data.
I'm interested in this concept for different data types, ex. floats, ulongs, etc. that cannot be easily represented by enum names or stored as an enum value.
As for string -> enum, the point of using an enum in the first place for me is that I can rely on intellisense to give me a constant that exists; I don't want to wait until compile time or runtime to find out. Passing in an actual string would be duck typing and that's something I definitely don't want to do in a strongly typed language.
I would suggest you create an enum and parse the string value into an enum member.
You can use the Enum.Parse method to do that. It throws ArgumentException if the provided value is not a valid member.
using System;
class Program
{
enum MyEnum
{
FirstValue,
SecondValue,
ThirdValue,
FourthValue
}
public static void doStuff(string constValue)
{
var parsedValue = Enum.Parse(typeof(MyEnum), constValue);
Console.WriteLine($"Type: { parsedValue.GetType() }, value: { parsedValue }");
}
static void Main(string[] args)
{
doStuff("FirstValue"); // Runs
doStuff("FirstValuesss"); // Throws ArgumentException
}
}
Extending core classes in javascript is dead easy. I get the impression it's not quite so easy in C#. I was wanting to add some things to the String class so that I could do stuff like:
string s = "the cat's mat sat";
string sql = s.smartsingleQuote();
thus giving me
the cat''s mat sat
Is that even feasible, or do I have to write a function for that?
Yes it is possible using Extension Methods - MSDN
Here is a sample code.
public static class Extns
{
public static string smartsingleQuote(this string s)
{
return s.Replace("'","''");
}
}
Disclaimer : Not tested.
Yes you can do this, with an extension method. It'll look something like that:
public static class NameDoesNotMatter {
public static string smartSingleQuote(this string s) {
string result = s.Replace("'","''");
return result;
}
}
The magic is the keyword "this" in front of the first argument. Then you can write your code and it'll work:
string s = "the cat's mat sat";
string sql = s.smartsingleQuote();
You cannot accomplish exactly what you are talking about as the string class is sealed
You can accomplish the aesthetic of this by creating an extension method
public static class StringExtensions
{
public static string SmartSingleQuote(this string str)
{
//Do stuff here
}
}
The this keyword in the parameter allows you to take that parameter and put it in front of the method name for easier chaining like you requested done in your question. This, however, is equivalent to:
StringExtensions.SmartSingleQuote(s);
It just depends on your preference at that point :)
Here is a good SO answer on extension methods
I'm trying to do something a certain way... but I'm certain there's a better way
public interface IMix
{
T Mix<T>(List<T> values) where T : IMix;
}
The problem with this is that if I want to "Mix" 5 values, then I need to do value1.Mix(others) but that is not clean. Plus, the type of T needs to be the same type as whatever class implements the interface. So, this doesn't really work.
I was thinking something like this:
public static class MixWrapper
{
public static T Mix<T>(List<T> values);
}
But that obviously won't work because I have to define the body in MixWrapper
EDIT: to clear up some misunderstanding, these are not real math averages, I could just as easily say "Fuse" or anything else. For example I could be trying to "average" a list some struct or other class.
EDIT 2:
One example could be a class like this
class Sequence : IMix
{
List<int> sequence;
double period;
double weight;
}
The "Mix" in this case would need to return a Sequence that was built this way: the resulting period is the weighted average of the periods based on the weight. The weight is the sum of the weights, and the sequence is the weighted average of the sequences after they have been timescaled down to the resulting period. Suffice to say, any complicated method that you could think of needs to be accounted for
If you want to calculate average of some list, then you can use LINQ:
var value = list.Average(x => x.SomeProperty);
Put the type T on your interface and just fill it with the same type as the class when you're implementing it:
public interface IMix<T>
{
T Mix(List<T> values);
}
public class ConcreteObjects : IMix<ConcreteObjects>
{
public ConcreteObjects Mix(List<ConcreteObjects> values)
{
// do mixing
}
}
This also leaves the door open for other classes to be able to mix ConcreteObjects if need be.
I think you're looking for an extension method.
You need to define a static method somewhere (some helper class, I suppose) like this:
public static T Average<T>(this List<T> list) where T : IAverage
{
return // average stuff
}
Now you just need to include your helper class with using and you can do something like this:
AverageClass implements IAverage
List<IAverage> list = new List<AverageClass>();
var average = list.Average();
I'm trying to create a wrapper around List to do some specific things I want, such as compute max min, extract specific values from some elements, etc.
I start with
public struct datum {
public UInt32[] chan;
public UInt64 sample_number;
public UInt32 time;
public UInt32 source_sector;
}
public class dataSet : List<datum> {
bool dirty=true;
....
}
the methods are typically like this (I want to know if the list has been modified as I have a max()/min() function that only parses the data when it has been modified and caches the values to reuse if the List has not been modified)
public new void Add(datum x ) {
base.Add(x);
this.dirty = true;
}
However, I'm not sure how to create a constructor. This syntax does not work.. how can I get this type of behavior?
public dataSet(int count) {
this = (dataSet) new List<datum>(count);
}
I also have this constructor, which seems to work fine (no compilation errors) though untested
public dataSet(List<datum> data) {
this.AddRange(data);
}
I came across a post that said that you should use a Collection and a List is used for speed. Though I need the speed, and I'm not sure why a Collection would be better?
--UPDATE--
I don't want to use linq as you can't create something that computes max/min simultaneously as efficiently as this:
public void recalculateMaxMin() {
foreach (var d in data) {
for (int i = 0; i < 16; i++) {
if (d.chan[i] > max[i]) max[i] = d.chan[i];
if (d.chan[i] < min[i]) min[i] = d.chan[i];
}
}
}
Thnx
I'm trying to create a wrapper around List to do some specific things I want, such as compute max min, extract specific values from some elements, etc.
Don't. Just use LINQ to Objects. That's what it was designed for:
var list = new List<int> { 10, 20, 30 };
var average = list.Average();
var max = list.Max();
// etc
In general, I would advise against deriving from List<T> anyway - that's not what it was designed for. However, if you must, you just chain from one constructor to a base constructor:
public dataSet(int count) : base(count)
{
// Add in any extra code you want to here. Probably none in this case.
// It would execute *after* the base constructor call.
}
See my article on constructors for more information about constructor chaining.
(I'd also strongly advise you to change the name - dataSet doesn't comply with .NET naming conventions, and DataSet would mean something else entirely to most .NET developers.)
You can never ever set "this" to something in C#. I think you are looking for this:
public dataSet(int count)
: base(count)
{ }
However in my opinion you should take a look at "System.Linq" namespace. I think what you are trying to implement has been done before by Microsoft. 'Select', 'Join', 'Where' and many other clauses has been already implemented in Linq. Also you can use "INotifyCollectionChanged" interface to implement the dirty thing.
Here are some references:
INotifyCollectionChanged
Linq
If you realy need to implement a complete List class with a new behavior, implementing "System.Collections.Generic.IList" interface is the only thing that will rock your idea in an advanced and perfect way. It's more customizable than inheriting from the List class and trying to change everything you have no access to.
Hope it helps
Cheers
public dataSet(int count)
: base(count) {
}
You can call the base type's constructor using base()
public dataSet(int count) : base(count)
{
// no need to implement anything here. base(count) will call the base
// type's constructor
}