Is limiting boxing thru these methods worth it? - c#

C# 3 btw...
So I am working on my AI blackboard. Part of that is an associative map, of string names to a gerneric values (object), right now the value is stored as a boxed value type or a string cast to an object.
So something like this:
public class ContextEntry
{
public string name;
public object value;
}
public class BehaviorContext
{
public ContextEntry AddEntry<T>(string name, T value)
{
//checks to see if T is an allowed type, create a ContextEnetry
//and adds it to map, returning a reference to the added entry
}
public bool GetValue<T>(string name, ref T val)
{
//look for entry, if found, do an as check with T,
//and then unbox the entry value into T
//otherwise return false
}
public bool GetValue(string name, ref object val)
{
//same as GetValue<T> but with object instead
}
public bool SetValue<T>(string name, T val)
{
//look for entry, if found, do an as check with T,
//and then box T into the entry value
//otherwise return false
}
public bool SetValue(string name, object val)
{
//same as SetValue<T> but instead checks val type is compatible with entry
}
protected Dictionary<string, ContextEntry> m_EntryMap = new Dictionary<string, ContextEntry>();
}
For those adding entries, they can keep a copy of ContextEnty around and directly access the value from there.
So what I am seeing is the constant boxing and unbox is hurting me, when it comes to frame time, as this is used alot.
I was wondering if doing something like this for ContextEntry would be better.
public interface IContextEntry
{
string Name {get; set;}
bool SetObj(object o);
void GetObj(ref object o);
}
public class ContextEntry<T> : IContextEntry
{
public bool SetObj(object o) { //do a compatibility check then unbox into value }
public void GetObj(ref object o) { //box value into o }
public T value;
}
Now i would keep a seperate dictionary of ContextEntry[T] per allowable type, and only search in right one if some one used GetValue[T] or SetValue[T]. If someone uses GetValue or SetValue, i would also keep a dictionary of IContextEntry with all entries. A user would use the templated versions of the functions often but also the non templated version often as well. When using a the non-templated versions, they would induce a virtual function call as well a boxing/unboxing.
Im wondering if its worth it. Any opinions?

Related

Convert object with list back to a class and find specific data from the object

I would like to create a function allow to get data from any classes with provide a key value, but I am stack when converting object back to the class. The following is my code.
var ListABC = new List<ABC>();
GetData(ListABC, typeof(ABC), "A1");
Here is my Function :-
Public void GetData(object obj, Type objType, string find)
{
// Note! not able to using (List<ABC>)obj, because you never know what tyoe of object will be pass in.
// How to get list data of "A1" after List ABC as a object? assume this function allow any classes.
}
Here is my class :-
public class ABC {
protected int _A1;
protected bool _B1;
protected string _C1;
public int A1
{
get
{
return this._A1;
}
set
{
this._A1 = value;
}
}
public bool B1
{
get
{
return this._B1;
}
set
{
this._B1 = value;
}
}
public string C1
{
get
{
return this._C1;
}
set
{
this._C1 = value;
}
}
}
As Daniel said, make GetData generic:
public void GetData<T>(IList<T> obj, string find)
{
}
and then call it like so:
GetData(ListABC, "A1");
You can even enforce constraints on T, for example:
public void GetData<T>(IList<T> obj, string find)
where T: IConvertible
{
}
If you don't want to implement an interface on the list item objects you will pass here, you could also pass a func:
public void GetData<T>(IList<T> obj, Func<T, string> idFunc, string find)
{
var matchingItems = obj.Where(o => idFunc(o) == find);
}
and call it like so:
GetData(ListABC, i => i.A1, "A1");
Edit: Do you just want ListABC.Select(i => i.A1) ?
If you want minimum change in your code. you can do it like below.
Although, making method generic is good idea, but as you are already passing type of ABC to the method, you are not required to make method generic.
here type you have passed is suggesting which type of data list is holding
Assumptions: you method's return type is void (so assuming you don't want anything to be returned. and also you are passing only one string find as a property to get so at a time you want data of only specified property.
if your requirements are simpler and scope of data is limited in your method only, you can always choose simpler way (which is easily understandable and readable)
try something like below,
public void GetData(object obj, Type objType, string find)
{
//as you are passing type of list here, you can use it.
if(objType == typeof(ABC))
{
List<ABC> list = (List<ABC>)obj;
//now use it.
//here we are getting the property with name as per find (name we passed in method)
PropertyInfo prop = objType.GetProperty(find);
//if there is no property with specified name, PropertyInfo object (prop) will be null
if (prop != null)
{
if (prop.PropertyType == typeof(int))
{
foreach (ABC abcObj in list)
{
object a1Data = prop.GetValue(abcObj);
int data = (int)a1Data;
}
}
}
}
}
Note: drawback of this approach is, you need to handle cases of different Types in this method. So if your method may accept big variety of type, you may not want to go with this idea.

c# store different settings in one object

I have an object that represents the current event that is taking place. This event contains a lot of settings. What is the best practice for storing all setting variables inside the event object?
The settings are stored in a database (right now in different columns based on the base class: ValueString, ValueInt, ValueBool, ValueDateTime, ValueFloat, ValueDecimal). A unique key represents the setting in the database.
As soon as i have loaded the events object i will store it in the local cache for quick access.
Should i cast everything to object? (Feels like un-needed casts to get/set settings)
class Event
{
// string = settings key
Dictionary<string, object> _settings;
public void AddSetting(string key, object value)
public object GetSetting(string key)
}
or should i have it in different dictionaries?
class Event
{
// string = settings key
Dictionary<string, string> _settingStrings;
Dictionary<string, int> _settingInts;
...
public void AddSetting(string key, string value)
public void AddSetting(string key, int value)
...
public string GetStringSetting(string key)
public int GetIntSetting(string key)
...
}
Any ideas?
You can store everything as an Object, but rather than performing a straight cast, use generics to build an easy to use API:
private IDictionary<string,object> _settings = new Dictionary<string,object>();
public void AddSetting<T>(string key, T value) {
_settings[key] = value;
}
public T GetSetting<T>(string key, T notFound = default(T)) {
object res;
if (!_settings.TryGetValue(key, out res) || !(res is T)) {
return notFound;
}
return (T)res;
}
The cast remains there, but the API hides it from the user: now the user can safely write
string searchPath = settingContainer.GetSetting<string>("searchPath");
int retryCount = settingContainer.GetSetting<int>("retryCount", -1);
I really do like dasblinkenlight's answer.
Except instead of wasting one column for each datatype, I would rather have only one column (likely a VARCHAR) on your datatable.
Advantages of this:
Faster reading (Only one indexed column)
Saving up storage (Only one varchar per row)
And then you can either use generics as mentioned, or cast the string object in your implementation to your wished type.

Using Enums that are in an external dll

I have a project I am working that will involve creating one DLL that will be used across multiple other sites. Inside this DLL we need to reference about 10 Enums. The values of these Enums however will be different for each site the DLL is used on. For example:
MyBase.dll may have a class MyClass with an attribute of type MyEnum.
MyBase.dll is then referenced in MySite. MyStie will also reference MyEnums.dll which will contain the values for the MyEnum type.
Is there any way to accomplish this? While building MyBase.dll, I know what enums will exist in side of MyEnums.dll. The problem is I cannot build MyBase.dll without specifically referenceing the MyEnums.dll, which is not created until the MyBase.dll is used in a specific project.
I hope that makes sense and hope I can find an answer here.
Thanks.
Edit:
Thanks for all the comments. It will take a few reads to completely understand, but let me try to give a better example of what I am looking at here.
Lets say the following code is in my DLL that will be put into various projects. Status is an enum.
public Class MyClass
{
private Status _currentStatus;
public Status CurrentStatus
{
get
{
return _currentStatus;
}
}
public void ChangeStatus(Status newStatus)
{
_currentStatus = newStatus;
}
}
What I want to be able to do is the define the possible values for Status in the individual projects. So in this DLL, I will never reference what values might be in the Status enum, I just have to know that it exists.
I hope that is a bit more clear on what I am trying to do.
If you want each client to see different enum values (in a different assembly version), then using an enum is a bad solution - changes will break client code...
Using an enum might work (as long as the enum names and assembly name are the same and the assembly isn't signed) - you could just swap the assembly. However, if a value is used anywhere in the code that isn't there at the end you'll end up with an exception. Also, you may have the explicitly number the values, to make sure different subsets of the values won't end up with the same number for different values or different numbers for the same value.
Instead consider using a dynamically built collection, e.g. a list, a dictionary or a database table. Or just give the same assembly with the same superset of enum values to everyone and let the users decide which values are relevant to them (perhaps use significant prefixes for values as a convention).
Or you could use a combination of the two...
Generate a different structure (different type name (or namespace) and assembly name) per site with different properties (according to site's profile) and one master structure for the service that accepts the structures. Have all the structures implement the same interface, which you expect to receive...
public interface IStatus
{
string GetKey();
}
public struct ClientXStatus : IStatus
{
private readonly string _key;
private ClientXStatus(string key)
{
_key = key;
}
// Don't forget default for structs is 0,
// therefore all structs should have a "0" property.
public ClientXStatus Default
{
get
{
return new ClientXStatus();
}
}
public ClientXStatus OptionB
{
get
{
return new ClientXStatus(10);
}
}
string IStatus.GetKey()
{
return _key;
}
public override bool Equals(object obj)
{
return (obj is IStatus) && ((IStatus)obj).GetKey() == _key;
}
public override int GetHashCode()
{
return _key.GetHashCode();
}
public static bool operator==(ClientXStatus x, IStatus y)
{
return x.Equals(y);
}
public static bool operator==(IStatus x, ClientXStatus y)
{
return y.Equals(x);
}
public static bool operator!=(ClientXStatus x, IStatus y)
{
return !x.Equals(y);
}
public static bool operator!=(IStatus x, ClientXStatus y)
{
return !y.Equals(x);
}
// Override Equals(), GetHashCode() and operators ==, !=
// So clients can compare structures to each other (to interface)
}
Use a master struct for the service:
public struct MasterStatus : IStatus
{
private readonly string _key;
private MasterStatus(string key)
{
_key = key;
}
// Don't forget default for structs is 0,
// therefore all structs should have a "0" property.
public MasterStatus Default
{
get
{
return new MasterStatus();
}
}
// You should have all the options here
public MasterStatus OptionB
{
get
{
return new MasterStatus(10);
}
}
// Here use implicit interface implementation instead of explicit implementation
public string GetKey()
{
return _key;
}
public static implicit operator MasterStatus(IStatus value)
{
return new MasterStatus(value.GetKey());
}
public static implicit operator string(MasterStatus value)
{
return new value._key;
}
// Don't forget to implement Equals, GetHashCode,
// == and != like in the client structures
}
Demo service code:
public void ServiceMethod(IStatus status)
{
switch (status.GetKey())
{
case (string)MasterStructA.OptionB:
DoSomething();
}
}
Or:
public void ChangeStatus(IStatus status)
{
_status = (MasterStatus)status;
}
This way you:
Use code generation to prevent collision of values.
Force users to use compile time checks (no int values or string values) by hiding values (as private) and only accepting your structures.
Use real polymorphism in the service's code (an interface) and not a error-prone hack.
Use immutable value types (like enums) and not reference types.
First you have to decide WHERE to put your constants. Then you can transform your enum to static properties.
For example:
public enum MyEnum
{
Value1,
Value2
}
Can be changed to (first naive approach):
public static class MyFakeEnum
{
public static int Value1
{
get { return GetActualValue("Value1"); }
}
public static int Value2
{
get { return GetActualValue("Value2"); }
}
private static int GetActualValue(string name)
{
// Put here the code to read the actual value
// from your favorite source. It can be a database, a configuration
// file, the registry or whatever else. Consider to cache the result.
}
}
This simply will provide required constants but you'll have to throw away compile-time check for the type if you'll need MyFakeEnum as parameter. For a better solution you can follow, for example, what Microsoft did (more or less) for System.Drawing.Color.
public sealed class MyFakeEnum
{
public static readonly MyFakeEnum Value1 = new MyFakeEnum("Value1");
public static readonly MyFakeEnum Value2 = new MyFakeEnum("Value2");
private MyFakeEnum(string name)
{
_name = name;
}
public static implicit operator int(MyFakeEnum value)
{
return GetActualValue(value._name);
}
private string _name;
}
Of course you should provide proper overides at least for Equals, GetHashCode and ToString.
Pro
It can be an upgrade from an existing enum. Code won't be breaked and you may just need to recompile.
You can use it as strongly typed parameter. For example: void DoSomething(MyFakeEnum value) is valid and callers can't pass something else (note that this is one of the reasons because enums are considered weak).
If you implement all the required operators you can use the normal syntax for comparison: value == MyFakeEnum::Value1.
With a little bit of code you may even implement the FlagsAttribute syntax.
You do not change the normal syntax of enums: MyFakeEnum.Value1.
You can implement any number of implicit/explicit conversion operators to/from your type and any conversion will be safe and checked in the point it's done (this is not true again with standard enums).
You do not have hard-coded strings that can be breaked by changes and won't be catched until they cause a run-time error (yes, run-time). Using, for example, a dictionary if you'll change the definitions then you'll have to search all your code for that string.
Cons
First implementation is longer because you have to write support code (but for any new value you'll simply add a new line).
Value list is fixed and must be known at compile time (this is not an issue if you're searching a replacement for an enum because it's fixed too).
With this solution you may save more or less the same syntax you had with standard enums.

Dealing with object parameters and generics

I have a the following generic methods:
public static string Glue(string prefix, string value)
{
return String.Format("{0}={1}&", prefix, value);
}
public static string Format<T>(string prefix, T obj) where T : struct
{
return Glue(prefix, (obj).ToString()); ;
}
public static string Format<T>(string prefix, List<T> obj) where T : struct
{
return String.Join("",obj.Select(e => Glue(prefix, e.ToString())).ToArray());
}
Now I'd like to call them with a parameter that comes in as an object and could be a variety of types.
I started writing some code and it started looking like it's going to have a very long if/else sequence:
// type of value is object, and newPrefix is string
if (value is int)
{
return Format(newPrefix, (int)(value));
}
else if (value is double)
{
return Format(newPrefix, (double)value);
}
...
Is there a way of avoiding this long sequence of if/else?
As stated there's not much of a way to make this simpler. The Format method is constrained to only taking value types (structs) which is easy to detect at the call site
if (value.GetType().IsValueType) {
// it's a struct
}
But there's no way to then to make the Format call happy as you can't provide the T type.
What you can do here is change Format slightly. The method call only uses the ToString method which is available on all types. You could remove the struct constraint and then call it with the value already in object form
public static string Format(string prefix, object obj) {
return Glue(prefix, obj.ToString()); ;
}
if (value.GetType().IsValueType) {
Format(newPrefix, value);
}

Adding generic properties to an object without having to cast them later?

I have an object, MySession, that has a hashtable for storing arbitrary properties with arbitrary types. The relevant part of the object definition is:
public class MySession
{
private Hashtable _sessionVars;
///
/// Set and retrieve session variables ala the traditional session managers.
/// So, SessionObject["var1"] can be used to set or retrieve a value for var1.
///
/// Name of the variable to access.
/// An object that was stored in the session under key.
public object this[string key] {
get {
if (_sessionVars.ContainsKey(key)) {
return this._sessionVars[key];
}
return null;
}
set {
if (this._sessionVars.ContainsKey(key)) {
this._sessionVars.Remove(key);
}
this._sessionVars[key] = value;
}
}
}
The annoying thing is that I have to properly cast the properties when I want to use them. For example:
MySession session = new MySession();
if ( (bool)session["valid"] == true ) { /* do something fun */ }
I would rather be able to do:
MySession session = new MySession();
if ( session["valid"] == true ) { /* do something fun */ }
Is it possible to do this in C#? If so, how?
Update: I do not want to use explicit methods for accessing the properties. The point is to be able to access them as simply as possible. Not like session.GetProperty(name, type) or something.
If you think carefully, you will realize that this is inherently impossible.
What if you write session[someTextbox.Text]?
What if you assign two different types to the same identifier?
Compiling such code would involve solving the halting problem to figure out what type each string would have.
Instead, you could make a strongly-typed wrapper class around HttpContext.Current.Session with properties that include casts in their getters.
If you are using .Net Framework 4.0 then you can do it by deriving your MySession class from DynamicObject and overriding the necessary methods.
Here is the code:
public class MySession : DynamicObject
{
//Why not use Dictionary class?
private Hashtable _sessionVars = new Hashtable();
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return true;
}
//You can make it private so that users do not use strings directly.
public object this[string key]
{
get
{
if (_sessionVars.ContainsKey(key))
{
return this._sessionVars[key];
}
return null;
}
set
{
if (this._sessionVars.ContainsKey(key))
{
this._sessionVars.Remove(key);
}
this._sessionVars[key] = value;
}
}
}
And this how you use it:
dynamic ses = new MySession();
ses.number = 5;
ses.boolean = true;
Console.WriteLine(ses.number > 4);
if (ses.boolean)
{
Console.WriteLine(ses.number - 1);
}
Console.ReadKey();
No need for casting or using string to access the new fields! If you are using Resharper you will get intellisense for existing fields too. If you need more functionality you can override other members too.
I personally end up having to handle the scenario where the session variable hasn't been set yet. Therefore, I end up with a method that looks like this:
public class MySession
{
...
public T GetValue<T>(string key, T defaultValue)
{
return _sessionVars.ContainsKey(key) ? this._sessionVars[key] as T : defaultValue;
}
}
Then T can be inferred. It can then be called like this (no casting required):
if (mySession.GetValue("valid", false))
{
// fun stuff here
}
I'm not really sure is "as T" works. If not, you can cast it to (T) done that before. "as T" would be nice if you've got inherited classes and such.
I typically derive off a class like mySession and call base.GetValue() in property getters I expose off the derived class.
If you're passing string (or any sort of object) keys, then it's impossible to do; the indexer method can only return one specific type, so you couldn't possible have it return a string or a double, for instance.
There are a couple of options: one, if this is a limited-scope class that doesn't need the flexibility of arbitrary keys, then you can just add explicit properties--maybe just for commonly used properties if you want to still be able to fall back on the object-returning indexer.
Or, you could add a generic Get method, like so:
public T GetValue<T>(object key) {
if(_hashSet[key] is T) {
return (T)_hashSet[key];
}
throw new InvalidCastException();
}
That doesn't get you much, though, since you'll still have to specify the type name, you're just moving it from the cast to the generic parameter.
EDIT: Of course, how you want to handle invalid casts is up to you, but throwing the exception mimics the behavior of the direct cast. As someone mentioned in another answer, if you also specify a parameter of type T in the signature, then it will get the correct type from that parameter.
Easy and best way to add session
public static void Add<T>(string key, T value)
{
var current = HttpContext.Current;
if (current == null) return;
current.Session.Add(key, value);
}
Example
public Model User
{
private string searchText
{
get { return SessionHelper.Get<string>("searchText"); }
set { SessionHelper.Add("searchText", value); }
}
}

Categories