Hot answers tagged

25

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 ...


15

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

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 ...


9

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? ...


8

Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)? No. Static cast will not result in undefined behavior. If it compiles then the cast is good (assuming integer/float types). Though some of your cast may potentially result in implementation defined behavior (depending on the sign-dness and size of the types). ...


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

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 &&...


7

I think you should keep it. const is not only meant for the compiler, but also for anybody reading your code. Even with the void* cast, you're still saying to readers "Trust me, I'm not touching your buffer!" and this is a valuable information that should not be discarded.


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

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

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

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

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

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

•Is this a bad idea? It is unnecessary. Nobody knows what most of the C++ programmers do but so far I only ever had one use for const_cast: to cast away a const from a type. You can also use it to partially take away constness: int do_things(const char* p); const char* const xyz = "abc"; do_things( const_cast<const char*>(xyz) ); The gain in ...


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

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. ...


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