473,785 Members | 3,032 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ValueType object

Hi,
Im a bit confused about when you cast a value type to an object.
I have a property grid wich stores the data and the defualt as
objects.

the data is limited to primitive types, structs and strings.
the structs only have primitive types.

however once ive set the data to the defualt,
if the data is a struct then any edits change the defualt data as well
wich was unexpected !

however it doesnt happen for primitive types.

I thought value types were always passed by value,
does this mean an object is actually able to behave
as a pointer to a struct ?

I gues il have to identify if its a struct and copy it with reflection ?...
but why is there not even Type.IsStruct ?
would this be the same as !IsClass&&!IsIn terface&&!IsPri mitive ?

Colin =^.^=
Jun 27 '08 #1
7 1696
I have a property grid wich stores the data and the defualt as
objects.
Well, you haven't really explained this setup... and unfortunately the
devil is probably in the detail here... can you add more info?
however once ive set the data to the defualt,
if the data is a struct then any edits change the defualt data as well
wich was unexpected !
I'm guessing that your structs are "mutable" - i.e. you can edit them
once created. This is almost always a big mistake; where "almost" means
"it would take a long discussion to explain some borderline scenarios
where it might just possibly make sense to have a mutable struct". In
general, structs should be /immutable/ - i.e. once created they never
change, but can be replaced (hence the need to provide CreateInstance
etc on a TypeConverter).
I thought value types were always passed by value,
does this mean an object is actually able to behave
as a pointer to a struct ?
Yes; the term is "box"; when you box a value-type to an object, an
object is created on the managed heap that encapsulates the value-type -
*broadly* as though you had a class with a single field member (although
it isn't really that).

If you then give two different bits of code the same boxed copy, then
they will be stomping all over each others values
I gues il have to identify if its a struct and copy it with reflection ?...
You can get the TypeConverter to do this for you; I'll knock up a demo...
would this be the same as !IsClass&&!IsIn terface&&!IsPri mitive ?
Well, I'd go for Type.IsValueTyp e

Marc
Jun 27 '08 #2
Et voila; an "editable" immutable struct via PropertyGrid

(quoted because it isn't actually an edit; it is a create)

Marc

using System.Componen tModel;
using System.Windows. Forms;

[TypeConverter(t ypeof(SomeStruc tConverter))]
public struct SomeStruct
{
private readonly int foo;
private readonly string bar;

public int Foo { get {return foo;}}
public string Bar { get {return bar;}}

public SomeStruct(int foo, string bar)
{
this.foo = foo;
this.bar = bar;
}
public override string ToString()
{
return string.Format(" {0}:{1}", Foo, Bar);
}
}

sealed class SomeStructConve rter : ExpandableObjec tConverter
{
public override bool
GetCreateInstan ceSupported(ITy peDescriptorCon text context)
{
return true;
}
public override object CreateInstance( ITypeDescriptor Context
context, System.Collecti ons.IDictionary propertyValues)
{
return new SomeStruct((int )propertyValues["Foo"],
(string)propert yValues["Bar"]);
}

// if you want to be able to edit the text directly
// rather than via the sub-properties, then you need
// to implement [Can]ConvertTo / [Can]ConvertFrom looking for
// string; note that ConvertTo will use ToString by
// default, so you just need [Can]ConvertFrom
}

class SomeType
{
private SomeStruct someValue;
public SomeStruct SomeValue
{
get { return someValue; }
set { someValue = value; }
}
}

static class Program
{
static void Main()
{
Application.Ena bleVisualStyles ();
using (Form form = new Form())
using (PropertyGrid grid = new PropertyGrid())
{
grid.Dock = DockStyle.Fill;
form.Controls.A dd(grid);
grid.SelectedOb ject = new SomeType();
Application.Run (form);
}
}
}
Jun 27 '08 #3
Here you go; a mock up, just showing a possible setup... actually I
switched to TypeDescriptor for the properties here for brevity, but in a
real system I'd probably use ICustomTypeDesc riptor /
TypeDescription Provider...

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Windows. Forms;

[TypeConverter(t ypeof(FlexiObje ctConverter))]
class FlexiObject
{
private readonly Dictionary<stri ng, objectvalues
= new Dictionary<stri ng, object>(StringC omparer.Ordinal IgnoreCase);

internal IEnumerable<Key ValuePair<strin g, object>Values
{
get { return values; }
}

public object this[string key]
{
get
{
object value;
values.TryGetVa lue(key, out value);
return value;
}
set
{
if (value == null)
{
values.Remove(k ey);
}
else
{
values[key] = value;
}
}
}
}
class FlexiObjectConv erter : TypeConverter
{
public override bool GetPropertiesSu pported(ITypeDe scriptorContext
context)
{
return true;
}
public override PropertyDescrip torCollection
GetProperties(I TypeDescriptorC ontext context, object value, Attribute[]
attributes)
{
FlexiObject obj = (FlexiObject)va lue;
List<PropertyDe scriptorprops = new List<PropertyDe scriptor>();
foreach (KeyValuePair<s tring, objectpair in obj.Values)
{
if (pair.Value != null)
{
props.Add(new
FlexiPropertyDe scriptor(pair.V alue.GetType(), pair.Key));
}
}
return new PropertyDescrip torCollection(p rops.ToArray(), true);
}
}
class FlexiPropertyDe scriptor : PropertyDescrip tor
{
private readonly Type propertyType;
public FlexiPropertyDe scriptor(Type propertyType, string name)
: base(name, new Attribute[0])
{
this.propertyTy pe = propertyType;
}
public override bool IsReadOnly
{
get { return false; }
}
private FlexiObject GetFlexi(object component)
{
return (FlexiObject)co mponent;
}
public override object GetValue(object component)
{
return GetFlexi(compon ent)[Name];
}
public override void SetValue(object component, object value)
{
GetFlexi(compon ent)[Name] = value;
}
public override Type ComponentType
{
get { return typeof(FlexiObj ect); }
}
public override bool CanResetValue(o bject component)
{
return true;
}
public override void ResetValue(obje ct component)
{
GetFlexi(compon ent)[Name] = GetDefaultValue ();
}
public override Type PropertyType
{
get { return propertyType; }
}
public override bool ShouldSerialize Value(object component)
{
return !object.Equals( GetValue(compon ent), GetDefaultValue ());
}
private object GetDefaultValue () {
Type type = PropertyType;
if (type == typeof(string)) return "";
if (type.IsValueTy pe) return Activator.Creat eInstance(type) ;
return null;
}
}
static class Program
{
[STAThread]
static void Main()
{
FlexiObject obj = new FlexiObject();
obj["Name"] = "Marc";
obj["DOB"] = DateTime.Today;
obj["ShoeSize"] = 9;
obj["Icon"] = System.Drawing. SystemIcons.Shi eld;
obj["FavColour"] = System.Drawing. Color.Red;
obj["UriKind"] = System.UriKind. Relative;

Application.Ena bleVisualStyles ();
using (Form form = new Form())
using (PropertyGrid grid = new PropertyGrid())
{
grid.Dock = DockStyle.Fill;
form.Controls.A dd(grid);
grid.SelectedOb ject = obj;
Application.Run (form);
}
}
}
Jun 27 '08 #4
many thanks again :)

I hadnt run into boxing before,
I think I understand it now thanks,
but primitive types dont seem to be affected.

all the structs are just structs,
and I have little control over them.

the data in the structs does need to be edited though thats the whole point
!

the structs could be anywhere such as in an array, or in a class or another
struct.

the defualts however arnt intended to be edited,
well at least not unintentionaly !

ive gone for Type.IsValueTyp e &&!Type.IsPrimi tive.

I cant beleive the amount of code thats gone into using this property grid
so far,
I realy wish id made my self a custom cell based control.

rather than create even more code with a type converter,
ive gone for the quick if dirty marshal way.

int size=Marshal.Si zeOf(uDefaults. data);
IntPtr ptr = Marshal.AllocHG lobal(size);
Marshal.Structu reToPtr(uDefaul ts.data, ptr, true);
udata.data=Mars hal.PtrToStruct ure(ptr, type);
Marshal.FreeHGl obal(ptr);

seems to work even if im a little uneasy about such code.
although it will only work where the struct is initially a null object,
this suits my needs. however editing fields of sub structs doesnt
work with the boxing method, as it seems to create another copy.
seems il have to use a typedreference, but that can only be used for
the struct fields, its a shame it cant be used for the primitive fields too.

Colin =^.^=

"Marc Gravell" <ma**********@g mail.comwrote in message
news:%2******** *********@TK2MS FTNGP06.phx.gbl ...
>I have a property grid wich stores the data and the defualt as
objects.

Well, you haven't really explained this setup... and unfortunately the
devil is probably in the detail here... can you add more info?
however once ive set the data to the defualt,
if the data is a struct then any edits change the defualt data as well
wich was unexpected !

I'm guessing that your structs are "mutable" - i.e. you can edit them once
created. This is almost always a big mistake; where "almost" means "it
would take a long discussion to explain some borderline scenarios where it
might just possibly make sense to have a mutable struct". In general,
structs should be /immutable/ - i.e. once created they never change, but
can be replaced (hence the need to provide CreateInstance etc on a
TypeConverter).
>I thought value types were always passed by value,
does this mean an object is actually able to behave
as a pointer to a struct ?

Yes; the term is "box"; when you box a value-type to an object, an object
is created on the managed heap that encapsulates the value-type -
*broadly* as though you had a class with a single field member (although
it isn't really that).

If you then give two different bits of code the same boxed copy, then they
will be stomping all over each others values
>I gues il have to identify if its a struct and copy it with reflection
?...
You can get the TypeConverter to do this for you; I'll knock up a demo...
>would this be the same as !IsClass&&!IsIn terface&&!IsPri mitive ?
Well, I'd go for Type.IsValueTyp e

Marc

Jun 27 '08 #5
There is no special reason that primatives aren't affected, except
that they are immutable. That is the key point here:
the data in the structs does need to be edited though
There is a 99.8% change this is a mistake [according to the department
of invented statistics].

structs in C# (or rather: ValueType in .NET) are not the same as
structs in C++; they are not a "light weight object" or however else
people think of them... the difference is the copy vs reference
semantics. I don't know enough to recommend which... but I firmly
believe that you'll have a much easier time of things if you either a:
switch to classes instead of structs, or b: make the structs
immutable.

Marc
Jun 27 '08 #6
Thanks Mark,

Nice example for the reason of the "CreateInstance " method existence, very
cool indeed!


"Marc Gravell" <ma**********@g mail.comwrote in message
news:ON******** ******@TK2MSFTN GP05.phx.gbl...
Et voila; an "editable" immutable struct via PropertyGrid

(quoted because it isn't actually an edit; it is a create)

Marc

using System.Componen tModel;
using System.Windows. Forms;

[TypeConverter(t ypeof(SomeStruc tConverter))]
public struct SomeStruct
{
private readonly int foo;
private readonly string bar;

public int Foo { get {return foo;}}
public string Bar { get {return bar;}}

public SomeStruct(int foo, string bar)
{
this.foo = foo;
this.bar = bar;
}
public override string ToString()
{
return string.Format(" {0}:{1}", Foo, Bar);
}
}

sealed class SomeStructConve rter : ExpandableObjec tConverter
{
public override bool GetCreateInstan ceSupported(ITy peDescriptorCon text
context)
{
return true;
}
public override object CreateInstance( ITypeDescriptor Context context,
System.Collecti ons.IDictionary propertyValues)
{
return new SomeStruct((int )propertyValues["Foo"],
(string)propert yValues["Bar"]);
}

// if you want to be able to edit the text directly
// rather than via the sub-properties, then you need
// to implement [Can]ConvertTo / [Can]ConvertFrom looking for
// string; note that ConvertTo will use ToString by
// default, so you just need [Can]ConvertFrom
}

class SomeType
{
private SomeStruct someValue;
public SomeStruct SomeValue
{
get { return someValue; }
set { someValue = value; }
}
}

static class Program
{
static void Main()
{
Application.Ena bleVisualStyles ();
using (Form form = new Form())
using (PropertyGrid grid = new PropertyGrid())
{
grid.Dock = DockStyle.Fill;
form.Controls.A dd(grid);
grid.SelectedOb ject = new SomeType();
Application.Run (form);
}
}
}

Jun 27 '08 #7
well I agree the struct v class is confusing thing to get used to.
and the pass by value/ref can be an awkward difference,
its not always the way you want it to be.

it would be expensive to replace all structs with classes,
not only that, the underlying library requires an array of structs for
various things.
especially for vertex data wich is itself a struct containing several
structs,
and has 200,000 instances.

although I dont edit this amount of data with the property editor,
some of the structs are the same type, and this I have little control over,
or would be too inconvenient to have struct and class duplicated.

its hard to use TypedReference however, as you cant use it as a field,
nor can you return it as a function value, you cant even pass it as a ref
nor cast it to anything not even an object or value type.
so you have to use it in the same function, or sub function.

but it does allow you to modify a field of a struct within a struct.
all you need is an array of FieldInfo wich contain the list of nested
members,
and the final fieldinfo, and ofc an object such as a class that holds the
struct.
im not sure how it would work on an aray of structs.
although the class does actually hold a boxed copy of the struct in a
dictionary.

//recursively called
public UData SetField(object value,List<Fiel dInfosubFfields )
{
....
if(...)
{
List<FieldInfof ields = new List<FieldInfo> ();
parentUdata = parent.SetField (null, fields);
if (fields.Count 0)
{
fields.Reverse( );
TypedReference typedReference =
TypedReference. MakeTypedRefere nce(parentUdata .data, fields.ToArray( ));
fieldInfo.SetVa lueDirect(typed Reference,value );
return null;
}
fieldInfo.SetVa lue(parentUdata .data,value);
return null;
}
...
}
Colin =^.^=

"Marc Gravell" <ma**********@g mail.comwrote in message
news:e3******** *************** ***********@k13 g2000hse.google groups.com...
There is no special reason that primatives aren't affected, except
that they are immutable. That is the key point here:
>the data in the structs does need to be edited though

There is a 99.8% change this is a mistake [according to the department
of invented statistics].

structs in C# (or rather: ValueType in .NET) are not the same as
structs in C++; they are not a "light weight object" or however else
people think of them... the difference is the copy vs reference
semantics. I don't know enough to recommend which... but I firmly
believe that you'll have a much easier time of things if you either a:
switch to classes instead of structs, or b: make the structs
immutable.

Marc

Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2828
by: Shawn B. | last post by:
Greetings, Is it possible to create a custom ValueType object in C#? Or must I use managed C++ for that? Thanks, Shawn
4
10099
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception since DBNull cannot be converted to int. I wrote the following method that looks up the column's data type and if it is a ValueType, returns the default value for the ValueType.
2
1407
by: Eric Newton | last post by:
Since String.Format has to box all value types to accomodate the params, and just for sheer efficiency, are there possibly any plans for a FormatValue method to minimize boxing? public static string FormatValue(string formatSpec, System.ValueType valueArgs); public static string FormatValue(string formatSpec, System.ValueType arg1) { return FormatValue(formatSpec,new ValueType { arg1 }); }
6
3061
by: Sahil Malik | last post by:
Okay, I can't inherit from System.ValueType. Why this restriction?? What I am trying to acheive is, create my own ValueType called "Money". So if I have a decimal that has value 1.93991, when cast'ed to Money, it gives me back "1.93", and I can easily write implicit and explicit casts to do a to-and-fro conversion. But I can't do such a conversion to-and-from from object, BECAUSE, my object inherits from System.Object, and I have no...
6
2143
by: Aryeh Holzer | last post by:
Let me start with a quote from the C# Programmers Reference (where I learned the cool word "covariance"): "When a delegate method has a return type that is more derived than the delegate signature, it is said to be covariant. Because the method's return type is more specific than the delegate signature's return type, it can be implicitly converted. The method is therefore acceptable for use as a delegate." It then goes on to give an...
1
5951
by: INeedADip | last post by:
PropertyInfo props = obj.GetType().GetProperties(); foreach (PropertyInfo p in props) if (p.PropertyType is ValueType) this._commonProperties.Add(p.Name, p.GetValue(request, null).ToString()); I get a warning that says p.PropertyType will never be ValueType....and it was right. After stepping through it the types are "System.Boolean" etc... I want to add all integer, string, and boolean types to NameValueCollection,
6
2034
by: Manikkoth | last post by:
Hello, Just curious to see why ValueType (which the base for all value types) is a class. I thought "class" would make a type a reference type. However, IsValueType for ValueType is returning true. --Musthafa
1
1533
by: Tony Johansson | last post by:
Hello! Everything not derived from System.ValueType is a reference type. I just wonder this ValueType type is derived from Object and it overrides the two methods Equals and GetHashCode which is derived from Object. What is the reson for overriding these two methods ? One mode question.
2
2322
by: Veeranna Ronad | last post by:
Hello, Our application gets datetime from an interface function. This function returns "ValueType". How to copy datetime content from this "ValueType" to DateTime variable? Thanks in advance and regards, Veeranna Ronad.
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10327
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10151
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.