My struct class:
public struct PinAndRadius
{
public string pinID { get; set; }
public string radiusID { get; set; }
public string getPinID()
{
return pinID;
}
public string getRadiusID()
{
return radiusID;
}
}
the method with a problem:
void mapArea_VE_PinDragged(double latitude, double longitude, object id)
{
foreach (var pin in pinRadiusCollection)
{
string ID = id.ToString();
//string newID = ID.Substring(0, 18);
if (!pin.Key.pinID.Equals(ID))
{
continue;
}
else if (pin.Key.pinID.Equals(ID))
{
var newLoc = createNewSearchLocation(latitude, longitude);
mapArea.VE_DeleteRadius(pin.Key.radiusID);
drawPoly(newLoc, pin.Value.xar_Radius);
pin.Key.radiusID = pollyID;
break;
}
}
}
The problem is that when I try to set pin.key.radiusID to pollyID, I get an error saying
Cannot modify the return value of 'System.Collections.Generic.KeyValuePair.Key' because it is not a variable...
Any ideas?
Structure in .net is value-type. This mean you can't get reference to PinAndRadius using pin.Key. You will get copy of pin.Key of type PinAndRadius. Then you haven't access to this copy and compiler tell you about this. In C++ terms it not l-value.
If you create struct always try make it immutable. Mutable structs are evil.
Simplest way to solve this problem is to make PinAndRadius as class.
By the looks of it, your pinRadiusCollection is a generic dictionary keyed by PinAndRadius; the error you're getting is letting you know you can't modify that object because it's being used as the key in your dictionary.
If your pins are supposed to be mutable, you should probably revisit how you're storing them.
Collections in .net are not set up to allow convenient modification of struct-type items contained therein. Despite this, mutable structs still offer cleaner semantics than any other kind of data type. To edit a struct held in a collection, simply copy it to a variable, edit that variable, and store it back:
var temp = myList[someIndex];
temp.SomeVield = whatEver;
myList[someIndex] = temp;
Note that it's generally better to have mutable structs expose their contents as fields than as properties. Some people may say mutable structs are evil because their semantics differ from classes, but that's like saying screwdrivers are evil because they make lousy hammers. Exposed-field structs don't work like class types, but structs where all fields are exposed all have the same semantics as each other. Those semantics differ from classes, but for cases where they're useful, they have no equal.
Incidentally, much of the bad reps "mutable structs" got was a result of the fact that mutating struct members other than exposed fields would often generate bogus code if applied to read-only structures. If you avoid having struct members which modify fields of this [it's perfectly safe for static struct methods to modify fields of structures received as ref parameters], those dangers don't apply.
I simply just changed the struct definition to a class.
Related
I have the following scenario (https://run.dlang.io/is/19OOW9):
import std.stdio;
void main(string[] args)
{
inter1 c1 = new foo();
foo c2 = new foo();
writeln("Origin=interface: ", typeof(c1).stringof);
writeln("Origin=class: ", typeof(c2).stringof);
}
interface inter1 {
}
class foo : inter1 {
}
I work with interfaces and have different implementations for them. Now I need to know which concrete implementation is currently being used. So in the example above, I would like to know from c1 that it is an instance of the class foo.
Is this possible in the language D?
I have already tried the possibilities of object (e.g. TypeInfo_Class) and std.traits. Unfortunately without success.
A workaround is, of course, to provide the interface with a suitable meta method (https://run.dlang.io/is/Xnt0TO):
import std.stdio;
void main(string[] args)
{
inter1 c1 = new foo();
foo c2 = new foo();
writeln("Origin=interface: ", c1.strategyName);
writeln("Origin=class: ", c2.strategyName);
}
interface inter1 {
#property string strategyName() const;
}
class foo : inter1 {
#property string strategyName() const {
return "foo";
}
}
However, this is cumbersome and unusual for D. I can well imagine that there is a better implementation of this.
Best regards
Thorsten
It is quite simple actually: first cast to Object, then fetch the typeid, after a null check:
Object o = cast(Object) your_object;
if(o is null) { /* i don't think this ever happens but you should check anyway */ }
writeln(typeid(o)); // will tell the class name
If you want to call a method on a specific class, you can just cast directly to your class, and again, null check it.
The intermediate cast to Object allows the typeid (aka classinfo) to succeed, whereas calling it directly on an interface always returns the typeid of the interface itself. This is because a D interface is defined to be very thin for maximum compatibility with other languages and doesn't automatically assume run time type information is actually present through it. But the cast to Object tells it you are assuming the RTTI is present, and then typeid will pull it.
Note that the typeid data doesn't provide a whole lot of information... it is mostly just what's needed for dynamic cast, comparison, and other features of the language runtime. But one convenience method it has is a class name and toString methods, which is why the writeln succeeds. But if you're looking for more detailed runtime reflection, you'll have to do it with a CT bridge function, or probably better yet, just write your own methods in the interface.
But if all you need is the class name, use that toString. It gives the fully-qualified name, including module name, so instead of foo, you will get like yourmodule.foo. You can just cut that off if you like by slicing at the dot.
I am very confused with properties in asp.net.
I just don't understand why we use properties and when I should use them. Could anybody elaborate a little on this.
public class Customer
{
private int m_id = -1;
public int ID
{
set
{
m_id = value;
}
}
private string m_name = string.Empty;
public string Name
{
set
{
m_name = value;
}
}
public void DisplayCustomerData()
{
Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
}
}
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.
Taken From CSharp-Station
There are a couple of good reasons for it. The first is that you might need to add validation logic in your setter, or actually calculate the value in the getter.
Another reason is something to do with the IL code generated. If you are working on a large project that is spread over multiple assemblies then you can change the code behind your property without the application that uses your assembly having to recompile. This is because the "access point" of the property stays the same while allowing the implementation code behind it to be altered. I first read about this when I was looking into the point of automatic properties as I didnt see the point between those and a normal public variable.
It's easy.
All fields in class MUST be private (or protected). To show fields to another class yyou can use properties or get/set methods. Properties a shorter.
P.S. Don't declare write-only properties. It is worst practices.
Properties are a convenient way to encapsulate your classes' data.
Quoting from MSDN:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
Let's consider two common scenarios:
1) You want to expose the Name property without making it changeable from outside the class:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
}
2) You want to perform some checks, or run some code every time the data is accessed or set:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = (String.IsNullOrEmpty(value)) ? "DefaultName" : value;
}
}
see:
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
The most important reason is for validation purpose in setter and manipulation part can be implemented in get part.
For Ex.
Storing weekdays, which should be from 1-7, if we take normal variable and declare it as public, anyone can assign any value.
But in Properties setter you can control and validate.
The next one you can use it for tracking. That means, you can know how many times set and get functions has been called by clients (statistical purpose, may be not useful frequently).
Finally, you can control read only, write only and read/write for the properties according to your requirements.
Possibly not specific to webservices, but...
I have a webmethod that returns:
List<Tadpole> myList = getList();
return new { data = myList , count = 5 };
It returns this as JSON.
my code checks myList[x].fishsticks which isn't actually part of the Tadpole class (so it errors). I am wondering, can I add a fishsticks attribute to myList somehow to avoid the error, so it gets included when I return the data?
Is there perhaps another elegant solution for doing this?
In your example, you'll have to add a fishsticks property to Tadpole.
public class Tadpole
{
//....
public int Fishsticks { get; set; }
}
Also, why are you adding a .Count property to your JSON type? Wouldn't it make more sense to just .data.Count, or just return the list and skip the wrapper entirely?
I haven't checked what properties of List<> get serialized lately, so it's possible that it's not included, but even if that's the case it would make more sense to do this:
List<Tadpole> myList = getList();
return new { data = myList , count = myList.Count };
Or, create a descendant class that overrides .Count and adds a serialization attribute.
Edit
If I remember correctly, anonymous/dynamic types are internally implemented as dictionaries, while classes are, well, not. (BTW, anonymous types and dynamic objects bring a host of performance and maintenance issues along with them.)
If you don't want to modify Tadpole for some reason, you could always create a descendant class:
public class HungryTadpole : TadPole
{
public int FishSticks { get; set; }
}
Strong typing is your friend and will save you many headaches down the road.
Pardon me if this question has already been asked. HttpContext.Current.Session["key"] returns an object and we would have to cast it to that particular Type before we could use it. I was looking at various implementations of typed sessions
http://www.codeproject.com/KB/aspnet/typedsessionstate.aspx
http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx
http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx
and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type of object into session, either as a method or as a separate wrapper. I thought we could use generics
public static class SessionManager<T> where T:class
{
public void SetSession(string key,object objToStore)
{
HttpContext.Current.Session[key] = objToStore;
}
public T GetSession(string key)
{
return HttpContext.Current.Session[key] as T;
}
}
Is there any inherent advantage in
using
SessionManager<ClassType>.GetSession("sessionString")
than using
HttpContext.Current.Session["sessionString"] as ClassType
I was also thinking it would be nice
to have something like
SessionManager["sessionString"] = objToStoreInSession,
but found that a static class cannot have an indexer. Is there any other way to achieve this ?
My thought was create a SessionObject which would store the Type and the object, then add this object to Session (using a SessionManager), with the key. When retrieving, cast all objects to SessionObject ,get the type (say t) and the Object (say obj) and cast obj as t and return it.
public class SessionObject { public Type type {get;set;} public Object obj{get;set;} }
this would not work as well (as the return signature would be the same, but the return types will be different).
Is there any other elegant way of saving/retrieving objects in session in a more type safe way
For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.
A downside of the technique is that consuming code needs to be aware of what keys to use for storage and retrieval. This can be error prone, as the key needs to be exactly correct, or else you risk storing in the wrong place, or getting a null value back.
I actually use the strong-typed variation, since I know what I need to have in the session, and can thus set up the wrapping class to suit. I've rather have the extra code in the session class, and not have to worry about the key strings anywhere else.
You can simply use a singleton pattern for your session object. That way you can model your entire session from a single composite structure object. This post refers to what I'm talking about and discusses the Session object as a weakly typed object: http://allthingscs.blogspot.com/2011/03/documenting-software-architectural.html
Actually, if you were looking to type objects, place the type at the method level like:
public T GetValue<T>(string sessionKey)
{
}
Class level is more if you have the same object in session, but session can expand to multiple types. I don't know that I would worry about controlling the session; I would just let it do what it's done for a while, and simply provide a means to extract and save information in a more strongly-typed fashion (at least to the consumer).
Yes, indexes wouldn't work; you could create it as an instance instead, and make it static by:
public class SessionManager
{
private static SessionManager _instance = null;
public static SessionManager Create()
{
if (_instance != null)
return _instance;
//Should use a lock when creating the instance
//create object for _instance
return _instance;
}
public object this[string key] { get { .. } }
}
And so this is the static factory implementation, but it also maintains a single point of contact via a static reference to the session manager class internally. Each method in sessionmanager could wrap the existing ASP.NET session, or use your own internal storage.
I posted a solution on the StackOverflow question is it a good idea to create an enum for the key names of session values?
I think it is really slick and contains very little code to make it happen. It needs .NET 4.5 to be the slickest, but is still possible with older versions.
It allows:
int myInt = SessionVars.MyInt;
SessionVars.MyInt = 3;
to work exactly like:
int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;
I need to log all the function parameters in a dozen functions.
Is there a way to pro grammatically determine all the parameters and their values (or at least their .ToString() value)? Perhaps via reflection?
Here is an example of how to do this with PostSharp
http://consultingblogs.emc.com/merrickchaffer/archive/2009/08/04/using-postsharp-to-log-method-entry-and-exit-in-net-code.aspx
You can also roll your own
http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/3/
To the best of my knowledge there's no way to use reflection to dynamically list and determine value of local variables. You can use reflection to get type information about the parameters of a method, but only the declared type - you can't automatically get information about the actual arguments, because the reflection metadata gives information about the method definition, not the specific values passed to it at runtime.
You can, however, do something like this:
static class Extensions
{
public static string GetTypeAndValue(this object obj)
{
return String.Format("{0}: {1}", obj.GetType().Name, obj.ToString());
}
}
Then, from within each method in which you want to perform logging, do something like
private void SomeMethodToBeLogged(string some_string, int some_int, bool some_bool)
{
Logger.Log(String.Format("SomeMethodToBeLogged({0}, {1}, {2})",
some_string.GetTypeAndValue(),
some_int.GetTypeAndValue(),
some_bool.GetTypeAndValue()));
}