473,608 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Null structs

Hello.

I have some structs in different namespaces/classes/other structs and I
sometime have to check if it contains something or not.

myStruct == null doesn't work.

I've currently done it by creating a IsNull method in my structs:

struct TestStruct {
public int Value;

public bool IsNull() {
return this.Equals(new TestStruct());
}
}

Is this correct? Is there another way?
--
S. Lorétan <http://www.tynril.info/(This link is in french. Sorry.)
Oct 2 '06 #1
2 9722
S. Lorétan a écrit :
I have some structs in different namespaces/classes/other structs and I
sometime have to check if it contains something or not.

myStruct == null doesn't work.
Value types (structs) cannot be null, they are always instanciated. By
the way, you are not checking if your instance contains something, you
are checking if your instance is ... instanciated.
I've currently done it by creating a IsNull method in my structs:

struct TestStruct {
public int Value;

public bool IsNull() {
return this.Equals(new TestStruct());
}
}

Is this correct? Is there another way?
As for this example, new TestStruct() creates an instance of TestStruct
with all its fields initialized with their default type value. For an
int (which is a value type), that is 0.
The default implementation of Equals for a value type uses reflection to
check fields equality. So in this case, IsNull will return true if Value
equals 0. I cannot assert the correctness of this behaviour.

Another way ? If your classes may not be instanciated, use reference
types (classes) instead of value types. In .NET 2.0, you could also use
the Nullable<Tclass .
Or have your value type manage its null state. I would have it this way :

interface INullable {
bool IsNull {
get;
}
}

struct TestStruct: INullable {
private int _Value;
private bool _IsNull;

public TestStruct(int value) {
Value=value;
}

public int Value {
get {
if (_IsNull)
throw new InvalidOperatio nException();
return _Value;
}
set {
_Value=value;
_IsNull=false;
}
}

public bool IsNull {
get {
return !_IsNull;
}
}
}
Mathieu
Oct 2 '06 #2
You can use the new c#2 sintax for nullable value types.
Forexample if you have structure
struct Foo
{
}

you can declare variable such as

Foo? f = null
or
Foo? f = new Foo();

the you can test
if(f == null)
{
}

or
you can use

if(f.HasValue)
{
}

The actuall value type is exposed via the Value property

f.Value returns the actuall value if the HasValue is true.

you can also use casting

Foo foo = (Foo)f;

Keep in mind that the Value property or casting return copy of the value, so
changing properties won't change the original value.
C# also has one new operator related to nullable value types - the ??
operator that can provide deault value if the nullable value type is null.
If you want to use this new feature of the language I'd suggest reading in
MSDN about it since it has some details related to arithmetic and
comparision operations when one of the operands is null. Just go in the MSDN
search tool and use "nullbale types" as a keyword.
--
HTH
Stoitcho Goutsev (100)
"Mathieu Cartoixa" <mathieu.cartoi xa@_NO_hotmail_ SPAM_.comwrote in message
news:45******** **************@ news.free.fr...
S. Lorétan a écrit :
>I have some structs in different namespaces/classes/other structs and I
sometime have to check if it contains something or not.

myStruct == null doesn't work.
Value types (structs) cannot be null, they are always instanciated. By the
way, you are not checking if your instance contains something, you are
checking if your instance is ... instanciated.
>I've currently done it by creating a IsNull method in my structs:

struct TestStruct {
public int Value;

public bool IsNull() {
return this.Equals(new TestStruct());
}
}

Is this correct? Is there another way?
As for this example, new TestStruct() creates an instance of TestStruct
with all its fields initialized with their default type value. For an int
(which is a value type), that is 0.
The default implementation of Equals for a value type uses reflection to
check fields equality. So in this case, IsNull will return true if Value
equals 0. I cannot assert the correctness of this behaviour.

Another way ? If your classes may not be instanciated, use reference types
(classes) instead of value types. In .NET 2.0, you could also use the
Nullable<Tclass .
Or have your value type manage its null state. I would have it this way :

interface INullable {
bool IsNull {
get;
}
}

struct TestStruct: INullable {
private int _Value;
private bool _IsNull;

public TestStruct(int value) {
Value=value;
}

public int Value {
get {
if (_IsNull)
throw new InvalidOperatio nException();
return _Value;
}
set {
_Value=value;
_IsNull=false;
}
}

public bool IsNull {
get {
return !_IsNull;
}
}
}
Mathieu

Oct 2 '06 #3

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

Similar topics

3
7644
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
9
2852
by: Steve Sargent | last post by:
Hi: I'm trying to debug the following code, and it keeps looping on the if statement: public static bool operator == (OnlineMemberNode first, OnlineMemberNode second) { if(first == null) {
5
2239
by: Bob Gregory | last post by:
Hi all, I'm utter C# newbie, do be gentle. VS2005 Express refuses point blank to install on my box, so I'm stuck with C# 1.0 unless someone can point me to a C#2.0 compiler elsewhere. I have an authentication system rigged up, which is working, but I'd like to be able to run a test like this <code>
61
3730
by: Marty | last post by:
I am new to C# and to structs so this could be easy or just not possible. I have a struct defined called Branch If I use Branch myBranch = new Branch(i); // everything works If I use Branch (myBranch + x) = new Branch(i); // it doesn't x is a loop iterator, i is an int for the constructor to define an array. What am I doing wrong here.
13
2495
by: Karch | last post by:
I find myself doing things like this all the time: if ( SomeObject != null && SomeObject.AnotherObject != null && SomeObject.AnotherObject.YetAnother != null && SomeObject.AnotherObject.YetAnother.HelpMePlease != null) { // Do Something }
51
4190
by: atv | last post by:
Hi, Just to check, if i set a pointer explicitly to NULL, i'm not allowed to dereference it? Why is that, it's not like it's pointing to any garbage right? Why else set it to NULL. I can remember some instances where i did just that and printf reported something like : (null). I'm asking because i read somewhere that it is not valid. I thought it simply wasn't valid to dereference a pointer who is _not_ set to point to anything.
76
4617
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the pointers are allowed to be null, while references must refer an existing variable of required type. The null is normally used for making optional parameters. But there is no way to pass null reference in C#. Something is missing.
8
2285
by: A. Anderson | last post by:
Howdy everyone, I'm experiencing a problem with a program that I'm developing. Take a look at this stack report from GDB - #0 0xb7d782a3 in strlen () from /lib/tls/i686/cmov/libc.so.6 #1 0xb7d4c2f7 in vfprintf () from /lib/tls/i686/cmov/libc.so.6 #2 0xb7d6441b in vsprintf () from /lib/tls/i686/cmov/libc.so.6 #3 0x08049ba0 in character_data::printf (this=0x800, argument=0x0) at character.c:198
2
4446
by: JennyWren | last post by:
I have an array of structs which I will be going through one-by-one to search for a matching value. This array might have elements added and removed later, so I don't want to have to update a defined size for the array. What I'd like to do is put a NULL struct at the end so that the end can be detected. Here's some code: typedef struct smfMolTrans { char molecule; /* molecule species */ char transiti; /* transition */ double...
0
8003
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
8498
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
8478
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
8152
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
8341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6817
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...
0
5476
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
4025
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.