Hot answers tagged

26

For casting, I have a much simpler method in mind: public static bool TryCast<T>(this object obj, out T result) { if (obj is T) { result = (T)obj; return true; } result = default(T); return false; } You don't need to detect nullable types manually since is operator already checks for it: 5 is int? returns true, so ...


22

You should have a look at Loop like a native!. Explicitly iterating over the indices is usually not the best way to do something in Python. By directly iterating over the string representation of n you won't even need the second argument (and you should remove it if the assignment/defined interface would not require it). This will help you a lot later, when ...


16

First you have it the wrong way around. You should not use the mutating version to supply data to the non-mutating function: const int& MyClass::operator[](int index)const { return const_cast<int&>(const_cast<MyClass&>(*this)[index]); } What happens if operator[] is modified and does mutate slightly the internal state? By ...


15

Converting everything via a float means that you get the wrong result whenever the input cannot be represented exactly as a double-precision floating-point number. For example, this is surely not acceptable: >>> StrictInt(10**23) 99999999999999991611392 There's an OverflowError when the input is too large to be represented as a float: >>>...


14

You should probably add IConvertible restriction on T, since it is used by Convert.ChangeType method. Also this check: typeof(T) == x.GetType() looks like an overhead. Convert.ChangeType does nothing if types match. For example, check out Int32 sources: int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } So you might as well just ...


13

If you know that the object is always either double or null, then that's exactly what the double? type can represent and you can convert to that using a cast: object obj = ...; double? doubleValue = (double?)obj; And once you have double?, you can cast it to decimal? and it will work both for the case when the value is null and when isn't: decimal? ...


13

I like my implementation as it's much more succinct Which isn't necessarily a good thing: we care about readable code, not about oneliners. It means we don't use 5 lines to write what can be written in 1 line but it also means we don't cram 5 lines in 1 line just for the sake of it. That being said: your implementation does the same as the example. I would ...


13

I'm not sure if you understand what boxing means because you use an int in the example. Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. and When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. and Unboxing extracts ...


13

As mentioned in another answer, iterating with indices in Python in most cases is a bad idea. Python has many methods and modules to avoid it. For your problem Python has powerful decimal module to work with decimal numbers. Here is how it can solve your problem: from decimal import * def count_even(number, length): return sum( d % 2 == 0 ...


11

You can test for emptiness of number by just if not number After testing for emptiness, you could go straight to an int by adding number = int(number) Inside the loops, when you test for i % 2 == 0:, and then put None as the loop body (that should really be pass), you could just test for if i % 2 != 0:, and replace None with the else body, and remove the ...


10

Just a quick shot at case "Greater Than": case "Greater Than": if (fieldTypeName == "int") { var one = Convert.ToInt32(givenValue); var two = Convert.ToInt32(expectedValue); return one > two; } if (fieldTypeName == "double") { var one = Convert.ToDouble(givenValue); var two = Convert.ToDouble(...


10

Since you are dealing with digits, you at some point must pick a base (in this case base 10). So converting the number to a string is not a bad way of getting the digits. I would keep it simple, and just check each digit and see if it is one of the digits you want. # Incorporating the other suggestions to loop over the chars directly rather than using an ...


8

If you are able to use C++11 in your application, then you can make use of the enable_if template to provide several overloads of your checked narrowing conversion: #include <limits> #include <stdexcept> #include <type_traits> template <typename I, typename J> static typename std::enable_if<std::is_signed<I>::value &&...


8

Use generics that's all: public static T? ConvertTo<T>(object x) where T : struct { return x == null ? null : (T?)Convert.ChangeType(x, typeof(T)); }


7

Starting from minor issues - please follow naming conventions (variables should be camelCased and methods PascalCased, do add access modifiers, give variables meaningful names). Your design breaks Open-Closed principle: Queue knows all the possible commands it can handle. In case when you need to add a new command you'll have to change the queue rather than ...


7

There are built-in converters in System.ComponentModel.TypeDescriptor namespace (System.dll). You don't have to write your own array and you have access to a bunch of pre-existing converters as well. This is a modified version to account for this: public static bool TryCast<T>(object obj, out T result) { result = default(T); if (obj is T) ...


7

Two things your could do: Refactor the common code into a method (like Initialize) and call that: private void Initialize() { base.GetProperty("FirstName"); base.GetProperty("LastName"); } public Person(Dictionary dictionary, string someString) : base(dictionary, someString) { Initialize(); } public Person(Dictionary dictionary, string[] ...


7

It stead of having a static method the basically does what polymorphism could do for you use polymorphism. public class Person { public string FirstName { get; private set; } public string LastName { get; private set; } public virtual void InitializeFromDictionary(Dictionary<string, string> row) { FirstName = row["FirstName"]; ...


7

The benefit of explicit null checking is that if the object is null, you return false without the performance impact of casting the object to your type.


6

The best solution is to make ComponentProperties know how to print itself. class ComponentProperties { friend std::ostream& operator<<(std::ostream& s, ComponentProperties const& d) { return d.print(s); } virtual std::ostream& print(std::ostream& s) const { return s << componentProperty_; ...


6

No it is not safe (It is undefined behavior): The called function may put stuff on the stack (or somewhere else) as the return value. Expecting the caller to deal with it at their end. If the caller does not deal with the return value appropriately then you have undefined behavior (the returned object may have a destructor that needs to be called for ...


6

Align your code better. It probably has tabs (replace them with space before pasting) in it that make reading it hard on a website. Please declare one variable per line: int t,ret,numthreads = 0,thread_success = 0,*iptr; You are not saving anything be doing this. But you are making it harder to read fot the next person. Anyway when you get a job (sorry I ...


6

You should really rewrite the main method as proper unit tests, with separate test cases, for example: private static void iterateMapKeysAsStrings(Map<String, ?> map) { for (String key : map.keySet()) { // nothing to do, invalid cast will be triggered for wrong type } } @Test(expected = ClassCastException.class) public void ...


6

In Python, pass is how you indicate that nothing happens; you shouldn't just put None on a line on its own. Alternatively, note that: if x: pass else: y() is the same as: if not x: y() except that the latter is much neater. You are right that the repeated int is bad form. You might find Asking the user for input until they give a valid ...


6

You didn't give much context to the code. But a few observations come to mind: Run and actionToApply sound much too active for the code that is being run. It seems like Evaluate and relationship would be more appropriate. Why are the cases inconsistently named? If you have "EqualTo", then I would expect "GreaterThan", not "Greater Than". Is string ...


6

General notes: The code is very 'stringly typed'. That makes it more difficult to understand and more error-prone. A string can have many possible values, so it's impossible to tell which actions and types this system supports just by looking at this method's interface - you'll have to investigate the code. Use enums instead - they're more self-documenting, ...


6

In general, the Java compiler knows the type of each variable, at every point during the execution. And when you operate on incompatible types, the program won't compile. When you cast an object to ArrayList<Vehicle>, the Java runtime environment can only ensure that the cast to ArrayList<something> succeeds, but due to backwards compatibility (...


6

This design looks to me like a massive violation of KISS. For a start, I don't see the benefit of CastTo and CastTo<T>. It seems to me that they could be eliminated by tweaking the wrapped conversion methods to work more like int.TryParse with two return values: one to say whether the conversion succeeded, and the other to tell you what the result was. ...


5

In my opinion the generic method is better for two reasons. First, it's cleaner, both for the client calling it because they don't have to cast and for the process of casting because it is only done in one place. Secondly, the client that's asking for the control knows the type of the control in this instance so it's very sensible, and good practice, to have ...


5

As ChrisW commented, this has been covered in depth at Stack Overflow. You're very close, but you should actually have the non-const version cast away the const-ness of the const version rather than how you're doing it. If you're calling a non-const method, you are operating on a non-const object. This means that the const cast is technically valid since ...


Only top voted, non community-wiki answers of a minimum length are eligible