Meaning of -1 in Programming [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I hate to ask this question on here, but I have searched both SO and Google to no success. I have seen in many places statements such as while(var != -1) and other statements, often loops, containing some sort of reference to -1. Is there a certain meaning to the use of -1, or is it just used as giving an integer representation of a boolean, or something like that? I have mainly seen this in C# programming if that is any help.

in C# -1 is just negative one. They're comparing a number against a number, seeing if it is indeed equal to negative one.
It's not uncommon to have an integer field that should only have positive values (for example, when representing an index in a list) and in such cases -1 is sometimes used to represent "not a valid value", for example, there is no item, and hence no index. They use -1 because an int is not nullable; they cannot assign null.
In theory this is probably a bad practice; it's using a "magic value" to mean something more than it really should. Ideally if "there is not valid" is a valid thing for the variable to represent it should be a nullable integer (int? or Nullable<int>) but this is an old convention (carried over from other languages without a feature for nullable ints) so it's hard to eliminate entirely.

Nothing special about it. It's just that in most frameworks and libraries, functions or methods that return an index of an element in a collection will return -1 when whatever you're looking for isn't in the collection.
For example, the index of the character b in the string foo would be -1 in JavaScript, .NET and, as far as I remember, Java as well.
So many devs have burned a rom in their minds saying that -1 is the index for not found items. Now you know why.

If you know that an int should always contain positive value (for instance an item count or an index in a list, -1 can be a kind of "reserved value", so you would for instance assign the count to -1 and as long as it's -1, you know no real value has been put in there, a bit like a "null"
other than that I don't think there's any special meaning to -1

Related

Expected 1 Actual 0 [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i am developing a Spring .net Application.
I have a Login Page with fields - LoginID Password
On Login-There is a form to be filled by the candidate
so after Login I check if the candidate has already filled form then the values are fetched from the database and shown in the form fields.
Now When the Candidate hasn't filled the form the database null rows for it and hence it gives me the above error..please tell me how should I resolve this error.
I tried checking if the obj is null but it does not go to to the next line to check of the obj is NULL it immediately throws the above mentioned exception
IT GIVES ERROR IN LINE 6 OF THE PAGE_LOAD FUNCTION
EXCEPTION:EmptyResultDataAccessException was caught
Incorrect Resultsize Expected 1 Actual 0
As I said above, I've never worked with Spring.NET, but taking a look at the documentation I believe you may be using the wrong method of the AdoTemplate class. QueryForObject, per the documentation, will `Execute a query mapping the result set to an object using a IRowMapper. Exception is thrown if the query does not return exactly one object.'
In your example, if the user is not registered, they won't be in the database, so 0 results will be returned. Hence the error Incorrect Resultsize Expected 1 Actual 0.
Try using the QueryWithRowMapper method, as it is (again, per the documentation) one of the methods for Mapping result sets to objects:
return (CandidateSession)template.QueryWithRowMapper(CommandType.StoredProcedure, "spGetCandidateSession", candidateMapper, parameters);
If the cast to CandidateSession does not fail, I would expect a null object to be returned.
Again, I've never worked in Spring.NET, so this is based on a fairly cursory reading of the documentation. Hopefully it will at least get you going down the right path.

Should methods return nil or empty array if no data was found/calculated? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is generic question and it's interesting what approach do you use guys and what are pros and cons? Sometimes methods return lists (for example, NSMutableArray or NSArray in obj-c) and my current approach is to return nil if there's nothing to return. It makes sense to return nil if it's just object of some native or custom class, however should we return alloc'ed/init'ed empty array if nothing was found?
The question is primarily targeted for objective-c but is also related to other languages. Objective-c has nice feature to call methods on nil, however this is not the case for all other languages. So it's also interesting to hear arguments from other devs (java, c# and PHP devs).
UPDATE It's strange why some are voting on closing the question. Design pattern related questions also could be described as personal opinion questions, however architecture & code quality questions are more important thing than just syntax questions.
There is not a single answer I believe.
For myself I decided to return the result of expected type if possible and NULL otherwise.
Say, in my homebrewed DAL the getAll method returns an empty array (list) - so it can be passed to PHP's foreach operator without raising an error.
On the other hand, the getRow method, which is supposed to return an associative array, returns NULL in case of none data found, as empty array would be as equally useless.
Returning a null and an empty container have two different meanings in my opinion. An empty container would mean, no result matched your query but it was successful, while a null result would mean something went wrong.
In the first case if you have written code somewhere to say:
print "You have found" + GetResults.Size() + " results"
You will be able to print that zero results matched the query. While if you decide on using null, you will have to add explicit checks.
I have also had some troubles with serializing result to JSON as a response to a web server request, later on I regretted that I chose to return null instead of empty array.
Return nil or whatever is clearly a non-thing. Don't do more work than needs to be done.
Returning an empty array may cause many useless pointers and structures to be allocated, when all you really need is to say, "I have nothing for you."
In Cocoa,
If you return a nil to some array you need to check afterwards, that you are not trying to access the array Index.
And it is good to return nil instead of an array without any object.

What is the lightest collection for store these values? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have many objects (such as 10.000, more or less). Every object has3 values :
Index (decimal, such as 0,0 <= X <= 100.000,9);
A Latitude value;
A Longitude value;
and I need to perform some search due to the Index value. Which will be the light approch to this? List<MyObject>? I know there are hashtable, but only for 2 values...
I read these values from a .csv file and I'll store it on application. WebForm, .NET 4.5.
The very lightest approach in terms of memory use is to put these into a struct, and hold them in an array of such structs. From what you say, you can't really pack data any tighter than that: two doubles and a decimal will occupy 32 bytes per entry, and the array of structs does not add any per-item overhead on top of this.
Having said that, this will slow down your coding and might save too little to matter in practice.
Why don't you use a Dictionary like this:
public class Position
{
public Latitude Latitude { get ; set ; }
public Longitude Longitude { get ; set ; }
}
public Dictionary<decimal,Position> Positions ;
Or use a Tuple in the dictionary:
public Dictionary<decimal,Tuple<Latitude,Longitude>> Positions ;
I believe the absolutely lightest approach would be bitmasking your values into an unsigned long, though it is slightly cumbersome.
To really get the grasp on which is the most efficient approach, i recommend trying them all with test values and looking at the output of sizeof() on them. that way you'd be really sure what's their runtime memory size.
I'd suggest a custom struct to hold your values, a tuple could work as well.

Array containing only 0 and 1 values [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need an array which will only contain the values 0 and 1. Will bool[] be good enough for me? Or is there something lighter weight?
EDIT:
I dont have memory constraints but that array is made and passes online All The Time with big files passes concurrently with that array. I want the maximun optimization so the big files wont be delayed
A bool is probably not the best way to do it. Depends how many numbers you have got.
It is important to realise that even though a bool is a single bit, it requires a full byte in memory.
A BitArray on the other hand takes care of this for you and is more space efficient, although ever so slightly less time efficient.
http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
Depends on your constraints, if it is not for a constrained environment a bool array will work just fine.
Bool Array is good enough. You can consider "false" as 0 and "true" as 1.
May be you need BitArray, the sequence of 1 and 0.
bool[] would do the trick... If your 0 & 1 numbers are in fact just "Flags" and not real numbers.
Using an Enum with the Flags attribute is another option. This would allow you to have an Intention Revealing Name for both boolean values.
[Flags()]
public enum TheFlags
{
NoneSet = 0,
FirstSet = 1,
SecondSet = 2
}
Then you can check if "First" is set like so:
TheFlags flags = TheFlags.FirstSet;
if (flags.HasFlag(TheFlags.FirstSet))
Console.WriteLine("First flag is set!");

How do I capture named groups in C# .NET regex? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I'm trying to use named groups to parse a string.
An example input is:
exitcode: 0; session id is RDP-Tcp#2
and my attempted regex is:
("(exitCode)+(\s)*:(\s)*(?<exitCode>[^;]+)(\s)*;(\s)*(session id is)(\s)*(?<sessionID>[^;]*)(\s)*");
Where is my syntax wrong?
Thanks
In your example:
exitcode: 0; session id is RDP-Tcp#2
It does not end with a semi-colon, but it seems your regular expression expects a semi-colon to mark the end of sessionID:
(?<sessionID>[^;]*)
I notice that immediately following both your named groups, you have optional whitespace matches -- perhaps it would help to add whitespace into the character classes, like this:
(?<exitCode>[^;\s]+)
(?<sessionID>[^;\s]*)
Even better, split the string on the semi-colon first, and then perhaps you don't even need a regular expression. You'd have these two substrings after you split on the semi-colon, and the exitcode and sessionID happen to be on the ends of the strings, making it easy to parse them any number of ways:
exitcode: 0
session id is RDP-Tcp#2
Richard's answer really covers it already - either remove or make optional the semicolon at the end and it should work, and definitely consider putting whitespace in the negated classes or just splitting on semi-colon, but a little extra food for thought. :)
Don't bother with \s where it's not necessary - looks like your output is some form of log or something, so it should be more predictable, and if so something simpler can do:
exitcode: (?<exitCode>\d+);\s+session id is\s+(?<sessionID>[^;\s]*);?
For the splitting on semi-colon, you'll get an array of two objects - here's some pseudo-code, assuming exitcode is numeric and sessionid doesn't have spaces in:
splitresult = input.split('\s*;\s*')
exitCode = splitresult[0].match('\d+')
sessionId = splitresult[1].match('\S*$')
Depending on who will be maintaining the code, this might be considered more readable than the above expression.

Categories